Behavior of retained property while holder is retained

Posted by Aurélien Vallée on Stack Overflow See other posts from Stack Overflow or by Aurélien Vallée
Published on 2010-03-23T23:04:33Z Indexed on 2010/03/24 0:33 UTC
Read the original article Hit count: 351

Filed under:
|
|

Hello everyone,

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.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about retain