3

示例代码中的许多地方我已经看到了@synthesize 变量的 2 种不同方式。例如,这里我采用 1 个示例按钮。@property(强,非原子)IBOutlet UIButton *logonButton;

1.@synthesize logonButton = _logonButton;

2.@synthesize 登录按钮;

在这两种方法中,推荐哪一种?

4

2 回答 2

7

简答

首选第一种方法。

长答案

第一个示例是声明为logonButton属性生成的 ivar 应该_logonButton代替与属性 ( ) 同名的默认生成的 ivar 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]; 
}
于 2012-06-13T14:26:00.493 回答
2
  1. 意味着为属性自动生成的 set/get 方法正在使用具有不同名称的 ivar - _logonButton。

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

  2. 表示为属性自动生成的 set/get 方法正在使用具有相同名称 logonButton 的 ivar。

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

于 2012-06-13T14:34:55.430 回答