2010年4月12日 星期一

Something about Category and Extention

Category 和 Extention 有著非常相似的使用方式, 然而卻還是有些不同的使用情境. 基本上, Extention 是個
"anonymous" Category.
讓我們來復習一下 Category 的寫法:

@interface MyClassName ( MyCategoryName)
// extra methods' definitions
- (void)superShrimp;
@end

然後再看看 Extention
@interface MyClassName ()
// extra methods' definitions
- (void)superShrimp;
@end


基本上, category 和 extention 都不能另外定義 instance members. 他們只能擴充原本 class 的 functionalities. 而在建置上, Extention 必須在 @implementation 裡面實作擴充的 method ( ex: superShrimp), 而 (MyCategoryName)的category 是不需要的.

所以, 當我們在玩 Objective-C 2.0 的時候, 有的時候就得用 Extention , 不然就戳塞了.

假設我們的 class declaration 如下:

@interface ThinkDifferent: NSObject {
NSString *_LoveIt;
}
@end

@interface ThinkDifferent(_Private_)
@property (nonatomic, retain) NSString *loveIt;
@end

@implementation ThinkDifferent
@synthesize loveIt = _LoveIt;
@end

這邊會出現 compiler error, 我猜想因為 Category 裡的 method 並不一定會出現在 main implementation 裡面,所以 compiler 會告訴你 "No declaration of property 'loveIt' found in the interface.

因此, 在這個例子裡面, 用 Extention 就可以讓 compiler 正常 pass 過.

Reference:
The Objective C Programming Language (Category and Extention)

沒有留言:

張貼留言