您的位置:首页 > 移动开发 > IOS开发

iOS类别和扩展(category和extension)

2015-06-25 21:39 519 查看

类别是一种为现有的类添加方法的方式。

利用Objective-c的动态运行时分配机制,可以为现有的类添加新方法,这种现有的类添加新方法的方式称为catagory,他可以为任何类添加新的方法,包括哪些没有源代码的类。

创建类别

@interface NSString(NumberConvenience)
- (NSNumber *)lengthAsNumber;
@end
代表向NSString类中添加方法

```

2.类别的实现

```
@implementation NSString (NumberConvenience)

- (NSNumber *)lengthAsNumber{

NSUInteger length = [self length];
//NSNumber *numObject = [NSNumber numberWithUnsignedLong:length];
//return numObject;
return [NSNumber numberWithUnsignedLong:length];

}
@end


3.类别的局限性

无法向类别中添加新的实例变量

名称冲突,即当类别中的方法与原始方法名称冲突时,类别具有更高的优先级,类别方法将完全取代原始方法从而无法在使用原始方法。

4.类别的作用

将类的实现代码分散到多个不同的文件或框架中

创建对私有方法的前向引用

向对象添加非正式协议

二、利用类别分散实现

我们可以将类的接口放入头文件中,从而将类的实现放入.m文件中

但不可以将@implementation分散到多个不同的.m文件中,使用类别可以完成这一工作

利用类别,可以将一个类的方法组织到不同的逻辑分组中,使编程人员更加容易的阅读头文件

举例代码:

头文件CatagoryThing.h包含类的声明和一些类别,导入Foundation框架,然后带有3个整型变量的声明

#import<Foundation/Foundation.h>
@interface CategoryThing : NSObject {
int thing1;
int thing2;
int thing3;
}
@end // CategoryThing
类声明之后是3个类别,每个类别具有一个实例变量的访问器,将这些实现分散到不同的文件中
@interface CategoryThing(Thing1)
- (void) setThing1: (int) thing1;
- (int) thing1;
@end // CategoryThing (Thing1)

@interface CategoryThing (Thing2)
- (void) setThing2: (int) thing2;
- (int) thing2;
@end // CategoryThing (Thing2)

@interface CategoryThing (Thing3)
- (void) setThing3: (int) thing3;
- (int) thing3;
@end // CategoryThing (Thing3)


类别可以访问其继承的类的实例变量,类别的方法具有最高的优先级

类别可以分散到不同文件中,甚至不同框架中

采用类别实现类的扩展(class extension)

没有名字的类别

可以在源代码里使用

可以添加实例变量,作为类的私有变量

可以将只读权限改成读写的权限

创建数量不限

在Thing.h文件中

#import <Foundation/Foundation.h>

@interface Things : NSObject

@property(assign) NSUInteger thing1;
@property (assign,readonly)NSUInteger thing2;

- (void)resetAllValues;
- (void)print;
@end


在Thing.m文件中

#import "Things.h"

//用没有名字的类别,来实现类的扩展
@interface Things ()
{
NSUInteger thing4;
}
//添加了新的属性thing3
@property(assign) NSUInteger thing3;
//改变了类声明中thing2的读写属性,但是写属性只能在本类中实现
@property(assign,readwrite) NSUInteger thing2;

@end

@implementation Things

- (void)resetAllValues{

self.thing1 = 10;
self.thing2 = 30;//这里是由于类的扩展中改变了thing2的属性,使他可写
self.thing3 = 598;
thing4  = 488;

}
- (void)print{

NSLog(@"%lu,%lu,%lu,%lu",self.thing1,self.thing2,self.thing3,thing4);
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: