Assume I have a interface like:
@interface it:NSObject
{
NSString* string;
}
@end
@implement it
-(id)init
{
if(self = [super init]){
self.string = [[NSString alloc]init];
}
}
-(void)dealloc
{
[self.string release];
[super release];
}
@end
If I use this class in another file and I call this:
it ait = [[it allow] init];
NSString* anotherString = [[NSString alloc] init];
ait.string = anotherString;
[anotherString release];
Will this cause the string alloced in init method of it a memory leak?
Since the string is not referenced and not autoreleased.
If I don’t alloc a string in the init method, what will happen when I call ait.string right before assign anotherString to it?
I think you need
in your interface and
in your implementation for self.string to work.
Then, when you do
in your init method the string will actually have a retain count of 2 because
[[NSString alloc] init]will return a string with a retain count of 1, and usingself.string =will retain the object again because the property is declared as ‘retain’. This will result in a memory leak, but you can fix by having:or similar.
Then, onto the actual question, if you do as above the string allocated in init wont leak when you reassign with
self.string =because properties marked as ‘retain’ release their current object before retaining the new one.If you don’t assign a string to
self.stringin the init method it doesn’t matter becauseself.stringwill just returnnil, which you can then deal with in your program.