@implementation TestClass
- (id) init
{
string = [[NSString alloc] init];
return self;
}
- (void) release
{
[string release];
}
@end
@implementation MainScreen
- (void) addItems
{
[myMutableArray addObject:[[[TestClass alloc] init] autorelease]];
}
- (void) release
{
[myMutableArray release];
}
My Question is when we release the myMutableArray, will it call the release method of TestClass or not?
No, that’s not how Cocoa memory management works. When you add the object to the array, the array expresses that it owns the object by sending the
-retainmessage. The array keeps this ownership until it itself disappears (i.e. is deallocated), then it no longer needs the object and sends it-releaseto relinquish ownership. The array does not need to retain or release the objects every time it is retained or released.To summarise: objects retain other objects when they need to take ownership of them, and release them when they no longer need that ownership.
This points to your memory management of the
stringivar being incorrect. You correctly take ownership of a zero-length string in-init(where I’m using “correctly” in a very loose sense), but then every time your object is released it releases the string. Consider:the above is likely to crash (and if it doesn’t, you’re very unlucky). You should release the string in
-dealloc, when your object finally doesn’t need it any longer. If you change the object referred to by the ivar, you also have to change the ownership.