2012年12月30日 星期日

Class Method (一)

有一段時間沒有更新這個網誌了
剛好趁跨年假期來打個一篇
這次是 Class Method,這是大部分的書本沒交到的使用方法,
不過要是學會的話會愛不釋手,因為可以省下打一堆字,
下面就開始這次的教學了。

這次是 Class Method

什麼是 Class Method ?
在 Objective-C 中的 [NSString string] 等方法就是 Class Method。
它同時也是符合 Auto Release 的功能。

那麼要如何寫一個 Class Method 呢?
其實很簡單,只要將一般的 Method 的開頭減號改成加號即可。
不過實際的內容要怎麼寫呢?

假設有兩個檔案為 Method.h 與 Method.m
一個 Class Method 都會是對外公開的 Method
所以 Method 的名稱都會打在 h 檔中

Method.h
+ (id)aMethod; // 這是一個不需要傳入值的 Class Method
+ (id)aMethodWithValue:(NSInteger)integer; // 這是一個需要傳入值的 Class Method

實作 Class Method 有三種方法:
一是直接回傳其他 Class 的 Class Method,這個就不用說了,
二是自己建立自己的 Class Method,這個是這次教學的重點,
三是建立一個 singleton 的 Class Method,這算是 Class Method 的一種變形,在下個教學會教到。

Method.m
+ (id)aMethod
{
	Method *method = [[[Method alloc] init] autoRelease];
	// 其實這跟一般的 Class 宣告方法一樣,
	return method;}

+ (id)aMethodWithValue:(NSInteger)integer
{
	Method *method = [[[Method alloc] initWithValue:integer] autoRelease];
	// 有傳值的 Class Method 就比較特別了,這要看你傳入的值要給哪個初始化的 Method,如果沒有這個 Method 就要自己建立一個了。
	return method;
}

這樣子在其他 Class 裡要用到這個 Class 的功能時就可以這樣子宣告,

Method *method = [Method aMethod];
或
Method *method = [Method aMethodWithValue:0];

這樣子就比一般 Class 宣告的方法短多了,而且又符合 Auto Release 的條件,
就不會忘了這個變數需要 Release 的問題。

未完續待

沒有留言: