在示例代码的很多地方我都看到了 @synthesize 变量的两种不同方式。例如,我在这里使用 1 个示例按钮。
@property(强,非原子)IBOutlet UIButton *logonButton;
1.@synthesize logonButton = _logonButton;
2.@synthesize登录按钮;
这 2 种方法中推荐哪一种?
简答
优选第一种方法。
长答案
第一个示例声明生成的 ivar 为logonButton
财产应该是_logonButton
而不是默认生成的 ivar,它与属性具有相同的名称(logonButton
).
这样做的目的是帮助防止内存问题。您可能会意外地将一个对象分配给您的 ivar 而不是您的属性,然后它就不会被保留,这可能会导致您的应用程序崩溃。
Example
@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];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)