实现Category
Category 的语法很简单,一样是用@interface 关键字在header中定义,在@implementation 与@end 关键字当中的范围是实作,然后在原本的class名称后面,用中括弧表示新增的category 名称。
举例来说,我们今天虽然写的是Objective-C语言,但是想要变得更像Small Talk一点,所以我们不想用NSLog
印出某个实例的信息,而是每个物件都有个把自己印出来的method,所以我们对NSObject建立了一个叫做SmallTalkish的category。
@interface NSObject (SmallTalish)
- (void)printNl;
@end
@implementation NSObject (SmallTalish)
- (void)printNl
{
NSLog(@"%@", self);
}
@end
如此一来,每个物件都增加了printNl
这个method。可以这么呼叫:
[myObject printNl];
前一章提到,我们在排序一个都是字符串的Array的时候,可以调用localizedCompare:
,但,假如我们希望所有的字串都一定要用中文笔划顺序排序,我们可以写一个自己的method,例如strokeCompare:
。
@interface NSString (CustomCompare)
- (NSComparisonResult)strokeCompare:(NSString *)anotherString;
@end
@implementation NSString (CustomCompare)
- (NSComparisonResult)strokeCompare:(NSString *)anotherString
{
NSLocale *strokeSortingLocale = [[[NSLocale alloc]
initWithLocaleIdentifier:@"zh@collation=stroke"]
autorelease];
return [self compare:anotherString
options:0
range:NSMakeRange(0, [self length])
locale:strokeSortingLocale];
}
@end
在存档的时候,档名的惯例是原本的class 名称加上category的名称,中间用加号连接,以我们刚刚建立的CustomCompare为例,存档时就要存成NSString+CustomCompare.h 及NSString+CustomCompare .m。