Search code examples
objective-cretaincount

Retain/ Release count problem. Clarification needed


Possible Duplicate:
check retain count

As i was playing with retain, release counts, i ran into a situation, i am not able to explain. Please help me understand it better:

  • There is a class O. It contains no variables and does nothing.
  • There is a class Count. It initializes O and increments, decrements counts for it
  • There is a UI nib with 2 buttons: Retain and Release

enter image description here

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    o = [[O alloc]init]; // At this moment [o retainCount] is 1 as expected
    ....

For every doRetain, counts increments as expected

- (IBAction)doRetain:(id)sender {
    [o retain];

    NSString *result = [[NSString alloc] initWithFormat:@"%d", [o retainCount]];    
    [label setText: result];  
    [result release];

}

Whenever release is called, count is decreased

- (IBAction)doRelease:(id)sender {
    [o release];

    NSString *result = [[NSString alloc] initWithFormat:@"%d", [o retainCount]];
    [label setText: result];
   [result release];

}

Consider 1 retains and 2 releases

enter image description here

  1. We start off with a retain count of 1, after alloc init sequence
  2. Followed by manual retain count goes up to 2
  3. We then decrease the count and it goes down to 1
  4. After which next decrease ..... seemingly does nothing Retain count is still 1
  5. This release refers to bad memory and crashes the app.

Please help me understand this behavior


Solution

  • If your retain count is 1 and you release, the object is no longer valid, and the releaseCount property is meaningless (and the results of which are unpredictable).

    Also, I know this is a test, but you create your strings with 'alloc', but never release them.

    When working with release and retain, you are only responsible for releasing YOUR OWN retains. Other objects may perform retains on the object in question, and they will, in turn, release them.

    If you get an object using a method containing the words alloc, copy or create, there is an implied retain on said object. Otherwise, you can assume that the object will go away after the current run loop, so if you want to hang onto a copy of the object, you'll need to perform a retain. When you're done with the object, do a release.