Jer*_*rry 0 iphone cocoa-touch objective-c
我将变量设置为IBOutlet.并@property(retain) @synthesize在我的.h和.m文件中使用.像这样:
@interface testViewController {
NSArray *keys;
}
@property (nonatomic, retain) NSArray *keys;
@end
@implementation SectionViewController
@synthesize keys;
Run Code Online (Sandbox Code Playgroud)
在许多书中,他们在viewDidUnload方法中将该对象设置为nil ,并使用release方法在dealloc方法中释放该对象.像这样:
- (void)viewDidUnload {
self.keys = nil;
}
- (void)dealloc {
[super dealloc];
[keys release];
}
Run Code Online (Sandbox Code Playgroud)
据我所知,如果我使用self.keys =零,结果是一样[keys release]的dealloc方法;对象键将是release,和"无"将不被保留.
为什么有些书每次都使用这种形式?
谢谢
首先,你的-dealloc方法会崩溃.你把电话拨到[super dealloc]了错误的位置.调用[super dealloc]将导致您的对象被释放,因此在此调用之后对ivars的任何引用都是引用垃圾内存.相反,你应该重写它
- (void)dealloc {
[keys release];
[super dealloc];
}
Run Code Online (Sandbox Code Playgroud)
现在回答你的问题.看起来你想知道人们为什么self.keys = nil在某些地方说,但是[keys release]在dealloc中使用.有几个很好的理由.第一个是某人(一个同事,你自己几个月后,或者一个用户,如果你开源你的代码)可能会覆盖-setKeys:这个类或子类中的setter .该setter可以假设关于简单无效的对象的状态-dealloc(例如,假设其他ivars /属性仍然包含有效值).如果做出这样的假设,那么调用setter就不安全了-dealloc.另一个难以追踪的原因是某人可能在您的对象上有一个有效的键值观察注册,用于密钥@"keys".调用self.keys = nil将触发KVO通知,这不是你想要在dealloc中做的事情.但是,说[keys release]完全会跳过KVO通知.