2012-06-13 26 views
3

许多地方在示例代码中我看到了2种不同的@synthesize变量。例如,我在这里取1个样本按钮。 @property(强,非原子)IBOutlet UIButton * logonButton;这2 @synthesize模式和建议哪个有什么区别?

1. @ synthesize logonButton = _logonButton;

2. @ synthesize logonButton;

这2种方法中哪一种被推荐?

回答

7

简短回答

第一种方法是优选的。

长的答案

第一个例子是声明,对于logonButton财产所产生的伊娃应该_logonButton,而不是默认生成的伊娃这将具有相同的名称与属性(logonButton)。

这样做的目的是帮助防止内存问题。您可能会无意中将一个对象分配给您的ivar而不是您的财产,然后它不会被保留,这可能会导致您的应用程序崩溃。

@synthesize logonButton; 

-(void)doSomething { 
    // Because we use 'self.logonButton', the object is retained. 
    self.logonButton = [UIButton buttonWithType:UIButtonTypeCustom]; 


    // Here, we don't use 'self.logonButton', and we are using a convenience 
    // constructor 'buttonWithType:' instead of alloc/init, so it is not retained. 
    // Attempting to use this variable in the future will almost invariably lead 
    // to a crash. 
    logonButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
} 
+0

在ARC条件不过,我看不出有什么区别。也许alloc/init方法会产生一些差异 –

+1

@KaanDedeoglu在使用ARC来使用下划线ivar装饰时,我仍然觉得它很重要。比如说你创建了一个自定义的getter/setter,并且在里面添加了一些特殊的逻辑。如果您不小心直接设置伊娃,您将绕过该逻辑,并有可能使应用程序的数据处于不需要的状态。 [本文](http://weblog.bignerdranch.com/463-a-motivation-for-ivar-decorations/)推断未能在ARC上使用下划线装饰时的潜在问题。 – FreeAsInBeer

+0

@FreeAsInBeer:感谢深度信息。这真的很有帮助。 –

2
  1. 就是说自动生成的组/该属性获取方法是使用具有不同名称的实例变量 - _logonButton。

    -(void)setLogonButton:(UIButton)btn {
    _logonButton = [btn retain]; // or whatever the current implementation is
    }

  2. 意思是自动生成的设置/获取属性方法是使用具有相同名称logonButton伊娃。

    -(void)setLogonButton:(UIButton)btn {
    logonButton = [btn retain]; // or whatever the current implementation is
    }