简单的是最容易忽略的。
不是最好,但你必须理解的写法
@property (nonatomic, retain) UILabel *someLabel;
-(UILabel *)someLabel
{
return _someLabel;
}
- (void)setSomeLabel:(UILabel *)someLabel
{
if (someLabel != _someLabel) {
[_someLabel release];
_someLabel = [someLabel retain];
}
}
如果你自定义了setter,推荐使用release释放对象
可能引起crash:
- (void)delloc
{
self.someLabel = nil;
[super delloc];
}
推荐:
- (void)delloc
{
[_someLabel release];
_someLabel = nil;
[super delloc];
}
在Apple官方文档中并不推荐在init和delloc中用Accessor方法,原因Apple也没有解释。
Don’t Use Accessor Methods in Initializer Methods and dealloc.
The only places you shouldn’t use accessor methods to set an instance variable are in initializer methods and dealloc.
stackoverflow中有人提到self.variable = nil
可以避免悬挂指针引起的crash,但是如果setter是自定义的,那么[variable release]
是更合适的选择。
Typically, you would either use self.variable = nil which has the benefit that it also sets the variable to nil (avoiding crashes due to dangling pointers), or [variable release] which is the fastest and may be more appropriate in a dealloc method if your setter has custom logic.
网友评论