您的位置:首页 > 其它

OC的分类和协议

2015-01-09 23:22 197 查看
分类和协议是OC中比较显著的俩个特点。分类的功能主要是实现类的扩展,协议则常常用在代理的实现上。

1、分类的声明

在分类的接口文件中,只允许新增方法,不能新增变量。语法形式:

@interface 类名 (分类名)

新增的方法声明;

@end

2、定义方法

在分类的实现文件中,对新增方法进行定义,语法如下:

@implementation 类名 (分类名)

新增的方法的定义{

语句;



@end

3、方法调用

分类的方法声明和定义之后,就可以进行调用了,语法如下:

[对象名 新增方法名]

实例:

#import <Foundation/Foundation.h>

@interface student : NSObject{

int val;

}

@end

#import "student.h"

@interface student (pupil)

-(int)intval;

@end

#import "student+pupil.h"

@implementation student (pupil)

-(int)intval{

val=200;

return val;

}

@end

#import <Foundation/Foundation.h>

#import "student.h"

#import "student+pupil.h"

int main(int argc, const char * argv[]) {

@autoreleasepool {

student *stu=[[student alloc] init];

NSLog(@"%i",[stu intval]);

}

return 0;

}

输出结果:200

协议实际上是一组方法列表,它不依赖于特定的类。使用协议可以使不同的类共享相同的消息。

1、协议的定义

一个协议的定义是放在头文件中的,其语法如下:

@protocol 协议名

(@optional或@required)方法声明;

@end

一般在方法声明前面,有2个关键字进行修饰:@optional,表示声明的方法是可选的;@required表示声明的方法是必须的。默认是必须实现的。

2、协议在类中的声明

要在类中使用协议,首先要在类中进行协议的声明,语法如下:

@interface 类名:父类名 <协议名>

@end

3、实现

协议实现语法如下:

@implementation 类名 (分类名)

类和协议中的声明方法的实现{

语句;



@end

实例:

#import <Foundation/Foundation.h>

@protocol protocalcc <NSObject>

-(void)go;

@end

#import <Foundation/Foundation.h>

#import "protocalcc.h"

@interface student : NSObject<protocalcc>

@end

#import "student.h"

@implementation student

-(void)go{

NSLog(@"go student");

}

@end

#import <Foundation/Foundation.h>

#import "student.h"

#import "student+pupil.h"

int main(int argc, const char * argv[]) {

@autoreleasepool {

student *stu=[[student alloc] init];

[stu go];

}

return 0;

}

输出结果:go student

在此程序中用到了协议继承,即协议2使用了协议1,语法如下:

@protocol 协议名2 <协议名1>

(@optional或@required)方法声明;

@end

在OC中,默认为创建的协议都是在协议中使用协议,协议名1为NSObject,语法如下:

@protocol 协议名 <NSObject>

(@optional或@required)方法声明;

@end

具有多个协议的使用

在大多数情况下,一个类中是可以使用多个协议的,@interface 类名:父类名<协议1,协议2,...协议n>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: