Question about the number of holds on objects in objects added to tables, Obj-C

advertisements

I'm developing an iPhone app and have a question about memory management. Let's say I have a class called Company with a NSNumber property(nonatomic,retain) called Id. I do this:

Company *company = [[Company alloc] initWithId:[NSNumber numberWithInt:1]];

Id should now have a retain count of 1? Then I do:

NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:company];
[company release];

What will the retain count on Id be now? Still 1? I should add that in the dealloc method in Company I do [self.Id release]. The problem is that when i do this in my app and later try to access [[array objectAtIndex:0] Id] it is out of scope. From my point of view the array retains company and therefore I should be able to access Id "through" the array. Is this correct?

Edit: Forgot to say that when I remove [self.Id release] from Company the app works, if it's there it crashes...

Thanks!


As for your specific question: yes, that's correct. The array retains any object added to it, and the Company instance should retain the Id object. (Aside: the property should be named id, not Id to follow Cocoa conventions.) This is assuming that you are retaining the value in the initWithId: method (using self.Id or [Id retain]).

I can't see anything wrong with your code. I think the error must be due to something you do between adding the Company object to the array and trying to access it again. Are you saying that the error occurs after you add the [self.Id release]; line to dealloc? That would also be very strange.

It sounds to me like either you have over-released the Company object, or the array itself has been released. Could you try to produce a small code example which produces the bug (instead of just saying "later I do this and...")?

A more general answer is that you shouldn't think about what the exact retain count might be. The retain count will often be higher than what you expected because of the internal workings of Cocoa. What you should keep track of is merely which classes take ownership of an object (NSArray and NSMutableArray do, for example) and in which situations your own code should/shouldn't take ownership of an object. So when you ask if the retain count is still 1, that's slightly beside the point. The issue is whether any object still has ownership of the object in question.