我一直想知道在类的dealloc方法中释放实例变量的正确方法。假设我有一个名为 myString 的实例变量,
// MyClass.h
{
NSString *myString;
}
@property(nonatomic,retain) NSString *myString;
// MyClass.m
@synthesize myString;
-(void)dealloc
{
[self setMyString: nil];
[super dealloc];
}
Apple 文档指出不要在初始化方法和 dealloc 中使用访问器方法
。我发现一些输入将实例变量设置为 nil 可以完成释放实例变量的工作(我在上面的 dealloc 方法中执行此操作)。那么,如果这是释放实例变量的正确方法,那么为什么 Apple 说不建议在 dealloc
方法中使用访问器呢?
最佳答案
您应该在对象上调用release;
-(void)dealloc {
[myString release], myString = nil;
[super dealloc];
}
它与多线程有关,其中可能有其他线程也在访问该属性。
但是你应该更多地使用 ARC
,这样你就不必将 dealloc
添加到你的任何对象,编译器将为你添加保留/释放消息编译时间。
Apple 发布了一个不错的 Transitioning to ARC Release Notes
关于objective-c - 在 dealloc 中释放实例变量的正确方法,Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22711644/