Understanding reference counting with Cocoa and Objective-C

后端 未结 14 1528
攒了一身酷
攒了一身酷 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:45

    The answers above give clear restatements of what the documentation says; the problem most new people run into is the undocumented cases. For example:

    • Autorelease: docs say it will trigger a release "at some point in the future." WHEN?! Basically, you can count on the object being around until you exit your code back into the system event loop. The system MAY release the object any time after the current event cycle. (I think Matt said that, earlier.)

    • Static strings: NSString *foo = @"bar"; -- do you have to retain or release that? No. How about

      -(void)getBar {
          return @"bar";
      }
      

      ...

      NSString *foo = [self getBar]; // still no need to retain or release
      
    • The Creation Rule: If you created it, you own it, and are expected to release it.

    In general, the way new Cocoa programmers get messed up is by not understanding which routines return an object with a retainCount > 0.

    Here is a snippet from Very Simple Rules For Memory Management In Cocoa:

    Retention Count rules

    • Within a given block, the use of -copy, -alloc and -retain should equal the use of -release and -autorelease.
    • Objects created using convenience constructors (e.g. NSString's stringWithString) are considered autoreleased.
    • Implement a -dealloc method to release the instancevariables you own

    The 1st bullet says: if you called alloc (or new fooCopy), you need to call release on that object.

    The 2nd bullet says: if you use a convenience constructor and you need the object to hang around (as with an image to be drawn later), you need to retain (and then later release) it.

    The 3rd should be self-explanatory.

    0 讨论(0)
  • 2020-11-22 17:47

    Matt Dillard wrote:

    return [[s autorelease] release];

    Autorelease does not retain the object. Autorelease simply puts it in queue to be released later. You do not want to have a release statement there.

    0 讨论(0)
提交回复
热议问题