是的
是的,是的。你差点
总是
这是非常有用的,因为Obj-C具有“nil消息传递”的特性:如果您向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