Search code examples
objective-ccopyretain

Behavior of retained property while holder is retained


I am a beginner ObjectiveC programmer, coming from the C++ world. I find it very difficult to understand the memory management offered by NSObject :/

Say I have the following class:

@interface User : NSObject
{
  NSString* name;
}

@property (nonatomic,retain) NSString* name;

- (id)   initWithName: (NSString*) theName;
- (void) release;

@end

@implementation User

@synthesize name

- (id) initWithName: (NSString*) theName
{
    if ( self = [super init] )
    {
        [self setName:theName];
    }
    return self;
}

- (void) release
{
    [name release];
    [super release];
}

@end

No considering the following code, I can't understand the retain count results:

NSString* name = [[NSString alloc] initWithCString:/*C string from sqlite3*/];
// (1) name retainCount = 1
User* user = [[User alloc] initWithName:name];
// (2) name retainCount = 2
[whateverMutableArray addObject:user];
// (3) name retainCount = 2
[user release];
// (4) name retainCount = 1
[name release];
// (5) name retainCount = 0

At (4), the retain count of name decreased from 2 to 1. But that's not correct, there is still the instance of user inside the array that points to name ! The retain count of a variable should only decrease when the retain count of a referring variable is 0, that is, when it is dealloced, not released.


Solution

  • You shouldn't override release, you should only override dealloc. When the retain count for user reaches zero, its dealloc will be called, releasing name.

    If you rename your release override to dealloc, the retain counts will behave as you expect.