Understanding reference counting with Cocoa and Objective-C

后端 未结 14 1676
攒了一身酷
攒了一身酷 2020-11-22 16:46

I\'m just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I\'m reasonably comfortable with C\'s malloc and f

14条回答
  •  旧巷少年郎
    2020-11-22 17:26

    NilObject's answer is a good start. Here's some supplemental info pertaining to manual memory management (required on the iPhone).

    If you personally alloc/init an object, it comes with a reference count of 1. You are responsible for cleaning up after it when it's no longer needed, either by calling [foo release] or [foo autorelease]. release cleans it up right away, whereas autorelease adds the object to the autorelease pool, which will automatically release it at a later time.

    autorelease is primarily for when you have a method that needs to return the object in question (so you can't manually release it, else you'll be returning a nil object) but you don't want to hold on to it, either.

    If you acquire an object where you did not call alloc/init to get it -- for example:

    foo = [NSString stringWithString:@"hello"];
    

    but you want to hang on to this object, you need to call [foo retain]. Otherwise, it's possible it will get autoreleased and you'll be holding on to a nil reference (as it would in the above stringWithString example). When you no longer need it, call [foo release].

提交回复
热议问题