繁体   English   中英

这2个@synthesize模式和推荐的有什么区别?

[英]What is the difference between this 2 @synthesize Pattern and which is Recommended?

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

1. @ synthesize logonButton = _logonButton;

2. @ synthesize logonButton;

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

简答

第一种方法是优选的。

答案很长

第一个示例声明为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]; 
}
  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
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM