Understanding reference counting with Cocoa and Objective-C

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

    Objective-C uses Reference Counting, which means each Object has a reference count. When an object is created, it has a reference count of "1". Simply speaking, when an object is referred to (ie, stored somewhere), it gets "retained" which means its reference count is increased by one. When an object is no longer needed, it is "released" which means its reference count is decreased by one.

    When an object's reference count is 0, the object is freed. This is basic reference counting.

    For some languages, references are automatically increased and decreased, but objective-c is not one of those languages. Thus the programmer is responsible for retaining and releasing.

    A typical way to write a method is:

    id myVar = [someObject someMessage];
    .... do something ....;
    [myVar release];
    return someValue;
    

    The problem of needing to remember to release any acquired resources inside of code is both tedious and error-prone. Objective-C introduces another concept aimed at making this much easier: Autorelease Pools. Autorelease pools are special objects that are installed on each thread. They are a fairly simple class, if you look up NSAutoreleasePool.

    When an object gets an "autorelease" message sent to it, the object will look for any autorelease pools sitting on the stack for this current thread. It will add the object to the list as an object to send a "release" message to at some point in the future, which is generally when the pool itself is released.

    Taking the code above, you can rewrite it to be shorter and easier to read by saying:

    id myVar = [[someObject someMessage] autorelease];
    ... do something ...;
    return someValue;
    

    Because the object is autoreleased, we no longer need to explicitly call "release" on it. This is because we know some autorelease pool will do it for us later.

    Hopefully this helps. The Wikipedia article is pretty good about reference counting. More information about autorelease pools can be found here. Also note that if you are building for Mac OS X 10.5 and later, you can tell Xcode to build with garbage collection enabled, allowing you to completely ignore retain/release/autorelease.

提交回复
热议问题