2011年5月15日 星期日

Foundation Framework-記憶體管理 CH17-1 Reference counting

//

// main.m

// CH17-1 Reference counting

//

// Created by jason on 2011/5/15.

// Copyright 2011 __MyCompanyName__. All rights reserved.

//

//#import


#import

#import

#import

#import

#import


int main(int argc, char *argv[])

{

NSAutoreleasePool *pool= [[NSAutoreleasePool alloc] init];

NSNumber *myInt = [NSNumber numberWithInteger:100]; // myInt 一個初值 ,不可以小於12 (我猜應該跟機器有關吧~

NSNumber *myInt2;

NSMutableArray *myArr= [ NSMutableArray array];

NSLog(@"myInt retain count = %lx", (unsigned long)[myInt retainCount]); //輸出目前的參考計數 count =1

[myArr addObject:myInt]; // myInt 加入 myArr 陣列中

NSLog(@"after adding to array =%lx", (unsigned long) [myInt retainCount]); // 輸出目前的參考計數 count =2 <= 會加一喔~

myInt2=myInt; // myInt2 指標值設為 myInt相同 , 由於系統不知道! 所以 參考計數不會加一

NSLog(@"after assignment to myint2=%lx", (unsigned long) [myInt retainCount]); // 輸出目前的參考計數 count =2 <= 不會加一喔~

[myInt retain]; // 使用 retain 訊息 幫他加一

NSLog(@"myInt after retain = %lx", (unsigned long) [myInt retainCount]);// 輸出目前的參考計數 count =3 <= 被加一了~

NSLog(@"myInt2 after retain= %lx", (unsigned long) [myInt2 retainCount]);// 由於myInt2 myInt 是指向相同的位址,所以 count =3

[myInt release]; // 釋放 myInt ,少了一個參考者

NSLog(@ " after release Int=%lx", (unsigned long) [myInt retainCount]); // 輸出目前的參考計數 count =2

[myArr removeObjectAtIndex:0]; // 刪除 myArr 中的物件 ,又少了一個參考者

NSLog(@"after removal from array = %lx", (unsigned long) [myInt retainCount]);// 輸出目前的參考計數 count =2

[pool drain];

return 0;

// return NSApplicationMain(argc, (const char **) argv);

}

沒有留言: