天天看点

Objective-C 类别(category)和扩展(Extension)1、类别(category)2、扩展(Extension)

1、类别(category)

使用Object-C中的分类,是一种编译时的手段,允许我们通过给一个类添加方法来扩充它(但是通过category不能添加新的实例变量),并且我们不需要访问类中的代码就可以做到,这点和javascript中使用原型来定义属性有点类似。

我们可以为一个类创建一个新的方法,而不需要在代码中编辑类定义。

下面就是定义并使用分类的例子程序,通过下面代码,我们可以给Object-C中的NSString 添加camelCaseString分类,使用camelCaseString方法,就可以去掉一个字符串中的空格,并将原有空格后的单词改写成大写(即将字符串转化为驼峰式)。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

#import <Foundation/Foundation.h>

//NSString 表示将要添加分类的类名称,该类必须是已存在的。

//CamelCase 是为类添加的方法名称。

//只能添加方法,不能添加变量。

//头文件命名惯例:ClassName+CategoryName.h

@interface

NSString

(CamelCase)

-(

NSString

*) camelCaseString;

@end

@implementation

NSString

(CamelCase)

-(

NSString

*) camelCaseString

{

//调用NSString的内部方法获取驼峰字符串。

//self指向被添加分类的类。

NSString

*castr = [

self

capitalizedString];

//创建数组来过滤掉空格, 通过分隔符对字符进行组合。

NSArray

*array = [castr componentsSeparatedByCharactersInSet:

[

NSCharacterSet

whitespaceCharacterSet]];

//把数组的字符输出

NSString

*output = @

""

;

for

(

NSString

*word in array)

{

output = [output stringByAppendingString:word];

}

return

output;

}

@end

int

main (

int

argc, 

const

char

* argv[])

{

NSAutoreleasePool

* pool = [[

NSAutoreleasePool

alloc] init];

NSString

*str = @

"My name is bill."

;

NSLog

(@

"%@"

, str);

str = [str camelCaseString];

NSLog

(@

"%@"

, str);

[pool drain];

return

0;

}

  

2、扩展(Extension)

你可以这样理解:扩展就是匿名分类,下面是一个扩展的例子:

@interface

MyClass :

NSObject

- (

float

)value;

@end

@interface

MyClass () {

//注意此处:扩展

float

value;

}

- (

void

)setValue:(

float

)newValue;

@end

@implementation

MyClass

- (

float

)value {

return

value;

}

- (

void

)setValue:(

float

)newValue {

value = newValue;

}

@end