NewbiZ
NewbiZ

Reputation: 2498

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.

Upvotes: 1

Views: 132

Answers (2)

stefanB
stefanB

Reputation: 79810

In User this:

- (void) release

Should be:

- (void) dealloc

You are mixing name and user memory management - each object has it's own memory.

At 4) you call your own release method which is not NSObject's release so I assume it will not work as expected. Change the name from release to dealloc on your User.

After the fix we can look at what other issues you have.

Upvotes: 2

Frank Schmitt
Frank Schmitt

Reputation: 25775

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.

Upvotes: 4

Related Questions