memory management in ios objective c
I am new to iOS and objective-C and although I've been struggling for a while to understand memory management I am disappointed in myself because I still have to get the full picture... My problem is that I do not understand how retaining a property of an object relates with retaining the whole object. Let's take the following code as an example:
@interface TestObject:NSObject { //TestObject declaration
NSNumber *firstNumber;
}
@property (nonatomic, retain) NSNumber *firstNumber;
@end
@synthesize firstNumber;
-(void) dealloc //Use standard synthesized getter and setter, write only custom
//dealloc
{
[f开发者_StackOverflow社区irstNumber release];
}
...and the following code that uses it:
-(IBAction) runClicked: (id) sender
{
TestObject *to1=[[TestObject alloc ] init];
to1.firstNumber=[NSNumber numberWithInt:10]; //retain count 1 on firstnumber
NSNumber *num=[to1.firstNumber retain]; //retain count 2 on firstnumber
[to1 release]; //retain count 1 on firstnumber because of 1 release in dealloc
}
I ran an analyze on the code and also ran the program with Leak instrument and no leaks were found by either. Isn't there a leak on firstnumber (accessible by num after main object release) since the number will not be usable by any pointer after *num is also destroyed at the end of function body?
Thank you so much for your time! Best regards, Florin.
No, there isn't a leak as first number is an autoreleased object.
精彩评论