- 使用#import,而非C++的#include
- 盡量用getter and setter
- 呼叫class member function要用 [self method名],而用父class要用[super method名]
- 在object-c當中,一定要使用self來呼叫member function,如果沒有使用self的話,他將會取得真實的記憶體給這個變數。
- 若我們要改寫super class的function,通常我們會呼叫super的member function,然後再做我們想做的事情。但如果做的事情與super function完全不同的話,你可能會先做完你要做的事情,在呼叫super function,但這是取決於你是否需要。
- 是否要明確表明我要override這個function--->不用。你就像一般implement function一樣去實做他就好。只要你知道他存在,且你也應該知道,因為他就在.h裡面,
- Object Lifecycle
- Creating object
- allocate memory to store object.
-->class method, 必須知道需要多少記憶體
-->然後我們會呼叫init,這也是自己實做的。
可以這樣寫: Person* aPerson = nil;
aPerson=[[Person alloc] init]; - initial object state
-->if(self = [super init])檢查self是否非nil,先呼叫上層的init,讓self有值,才能繼續往下作。
-->init method可以多載 - Memory management
- Destroying objects
-->alloc與dealloc應平衡,但不應該直接呼叫dealloc。
-->alloc和copy兩個method會建立物件當count=1
-->retain將retain count+1, release將retain count-1
-->當retain count =0, object就會自動喚起dealloc
-->當你release之後,知道他已經dealloc了,你就把local pointer(like aPerson)設成nil,之後用aPerson來處理事情就不會crash.
-->在dealloc實做當中,最後記得把[super dealloc]這將是少數直接呼叫dealloc的時候。 - if(name != newName) 先 [name release] 再 [newname retain]
- retain是用reference, copy算是另一個副本
- 在object-c當中,所有東西都是pointer.
- 在記憶體管理部份,永遠使用:alloc, retain, copy和release。
copy跟retain的差別在於:copy是有副本的。別人改了不會影響到本身,但retain就會有影響。 - - (void)setName:(NSString *)newName {
if (name != newName) {
[name release];
name =[newName retain];
}
}
這是為了保證若傳進來的是自己內部的字串,一樣可以運作。
而為什麼不直接寫name = newName呢?何必這麼麻煩寫這判斷式?
這是因為要把reference留給自己,不要讓別人把他dealloc掉,若是別人把他dealloc,而之後我們要去access他...那就會有問題。 - 還有另一個選擇:autorelease。當你在function宣告一個物件,你想要把他回傳(在C++是不對的!但object-c似乎可以這樣寫,的確是蠻方便的。),那就告訴compilier說,之後在自己release。
- 若你是用NSMutableString *string = [[NSMutableString alloc] init];
那要記得[string autorelease];
但若是NSMutableString *string = [NSMutableString string];
那我們就不用管他,他會自動release - 有另一個叫做property的東西(在header file中是 @property),他可以取代自己寫的getter 和setter。系統會直接產生這些給你。
property還可以特別指明要readonly。如此就只有getter會產生
而property還有三種policy: assign, retain和copy。assign: 當他產生了setter, 他不會retain新的物件,也不會release舊物件,他只會去assign而已。retain就是一般的認知,release舊物件並retain新物件。而copy就是release舊物件並copy新物件。
而在implement file則用@synthesize來作呼應。
@synthesize age = numberOfYearsOld; 這行表示numberOfYearsOld是原本class定義的member,而synthesize可以定義另一個變數來代表他。 - 當然你還是可以另外有setter和getter,用來作為更複雜的行為。而這就是一種複寫函式。
- 當你使用property在客製化的class中,你就要小心dot語意和property。
name = @“Fred”; // accesses ivar directly!
self.name = @“Fred”; // calls accessor method,他會呼叫synthesize self-name method
注意投影片p.51 - 在宣告的時候,前置+代表這是class method. 你可以用class name來呼叫。而前置-代表這是物件method. 你可以在物件上呼叫他。
- array最後一定是nil。這是因為要阻止一直讀取array下去。就像是char c string一樣。而是否有可能在array中間插入nil呢?不行!因為array只能擁有物件,而nil不是個物件。
2010年10月24日 星期日
Stanford iphone Lecture 3 in 2010 Winter
這是筆記不是老頭教的!
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言