在dealloc中释放对象

时间:2010-07-29 07:59:18

标签: objective-c

在我的Objective-C类中,我allocrelease一个对象多次。我还必须在dealloc中发布它。但如果它之前已经发布,我可能会崩溃。释放后将对象设置为nil是否合法?在什么情况下这会是错误的并导致更多问题?

1 个答案:

答案 0 :(得分:2)

是的。正如你提到的那样,你几乎总是 应该在发布后将其设置为nil。如果您再也不会访问它(例如dealloc)或者之后立即将其设置为其他内容,则您不需要。

这是非常有用的,因为Obj-C具有“nil messaging”的功能:如果你向nil发送消息,它不会崩溃,它只是没有做任何事情。所以:

MyClass *obj = [[MyClass alloc] init];
[obj doSomething]; // this works
[obj release]; // obj is now invalid
[obj doSomething]; // and this would crash

// but...
MyClass *obj = [[MyClass alloc] init];
[obj doSomething]; // this works
[obj release]; // obj is now invalid
obj = nil; // clear out the pointer
[obj doSomething]; // this is a no-op, doesn't crash

基于您的评论的另一个例子:

// we have an object
MyObject *obj = [[MyObject alloc] init];

// some other object retains a reference:
MyObject *ref1 = [obj retain];

// so does another:
MyObject *ref2 = [obj retain];

// we don't need the original reference anymore:
[obj release];
obj = nil;

[ref1 doSomething]; // this works
// now we're done with it
[ref1 release];
ref1 = nil;

// but someone else might still want it:
[ref2 doSomething]; // this works too!
[ref2 release];
ref2 = nil; // all cleaned up!

阅读Memory Management guidelines