这2个@synthesize模式和推荐的有什么区别?
示例代码中的许多地方我已经看到了2种不同的@synthesize变量方式。 例如,我在这里采取1个样本按钮。 @property(强,非primefaces)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]; }
-
意味着属性的自动生成的set / get方法使用具有不同名称的ivar – _logonButton。
-(void)setLogonButton:(UIButton)btn {
_logonButton = [btn retain]; // or whatever the current implementation is
} -
意味着属性的自动生成的set / get方法使用具有相同名称logonButton的ivar。
-(void)setLogonButton:(UIButton)btn {
logonButton = [btn retain]; // or whatever the current implementation is
}