代码之家  ›  专栏  ›  技术社区  ›  Pablo

释放dealloc中的对象

  •  2
  • Pablo  · 技术社区  · 15 年前

    在我的Objective-C一班 alloc release dealloc . 但如果它已经被释放之前,我可能会崩溃。将object设置为 nil 在释放它之后?在什么情况下,这会是错误的,并导致更多的问题?

    1 回复  |  直到 15 年前
        1
  •  2
  •   jtbandes    15 年前

    是的 是的,是的。你差点 总是

    这是非常有用的,因为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