I was reading the apple documentation for memory management, and came across something that I just don't understand. Basically, I don't understand why one does not need need to retain an instance variable through the "getter" method. I wrote this little program to see what would happen. I thought there would be a crash, but I am obviously missing something.
// main.m
// Test
//
#import <Foundation/Foundation.h>
#import "Test.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
//Initialize the test object
Test *t = [[Test alloc] init];
//Set the value to 5
[t setMyNum:[NSNumber numberWithInt:5]];
//Save a temp number that points to the original number
NSNumber *tempNum = [t myNum];
//release old number and retain new
[t setMyNum:[NSNumber numberWithInt:7]];
//Shouldn't this crash because tempNum is pointing to a deallocated NSNumber???
NSLog(@"the number is %@",tempNum);
[p drain];
return 0;
}
Doesn't tempNum point to a deallocated object??
All help is appreciated.
EDITThis is the code in the getter and setter methods
#import "Test.h"
@implementation Test
- (void)setMyNum:(NSNumber *)newNum {
[newNum retain];
[myNum release];
myNum = newNum;
}
-(NSNumber *)myNum {
return myNum;
}
@end
As you can see I am calling release on the old object.
EDITIt was suggested, and I thought rightfully so that the reason the tempNum is still around is because it hadn't been autoreleased from the pool yet. But even after moving the [pool drain] to right before the NSLog message, there is not crash??? Weird.