refer to Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009)
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSNumber *myInt = [NSNumber numberWithInteger: 100]; // retainCount =1 in init
NSNumber *myInt2;
NSMutableArray *myArr = [NSMutableArray array];
// retainCount =1 ,
NSLog (@ ” myInt retain count = %lx ” ,(unsigned long) [myInt retainCount]);
[myArr addObject: myInt]; // retainCount =2
NSLog (@ ” after adding to array = %lx ” ,(unsigned long) [myInt retainCount]);
myInt2 = myInt; // retainCount =2, 沒有用copy以後可能會有問題
NSLog (@ ” after asssignment to myInt2 = %lx ” ,(unsigned long) [myInt retainCount]);
[myInt retain];// retainCount =3
NSLog (@ ” myInt after retain = %lx ” ,(unsigned long) [myInt retainCount]);
NSLog (@ ” myInt2 after retain = %lx ” ,(unsigned long) [myInt2 retainCount]);
[myInt release]; // retainCount =2 , release後減少1
NSLog (@ ” after release = %lx ” ,(unsigned long) [myInt retainCount]);
[myArr removeObjectAtIndex: 0]; // retainCount =1, 移除後減少了1
NSLog (@ ” after removal from array = %lx ” ,(unsigned long) [myInt retainCount]);
[pool drain];
return 0;
}
myInt retain count = 1
after adding to array = 2
after asssignment to myInt2 = 2
myInt after retain = 3
myInt2 after retain = 3
after release = 2
after removal from array = 1
沒有留言:
張貼留言