您的位置:首页 > 其它

关于OC的协议和委托,转载一篇博文

2014-04-17 21:14 309 查看
在Object-C中,委托和数据源都是由协议实现的。协议定义了一个类与另一个类进行沟通的先验方式。

它们包含一个方法列表,有些是必须被实现的,有些是可选的。

任何实现了必需方法的类都被认为符合协议。

1、定义协议

定义协议的方式与定义类的类的方式非常相似。

@protocol MyProtocol <NSObject>

- (void)firstMethod;

- (void)secondMethod;

@end

2、定义一个类

这个类,本应实现firstMethod 和 secondMethod 方法,但是由于各种原因,并没有直接实现。

而是先这两个函数的功能“承包”给另外一个类(也就是代理)

//.h

@interface MyClass : NSObject {

id <MyProtocol> delegate;

}

- (void)oneMethod;

@end

//.m

@implementation MyClass

- (void)oneMethod {

if(!delegate) {

return;

}

int type = random() % 10;

if(type < 5){

[self.delegate firstMethod];

} else {

[self.delegate secondMethod];

}

}

@end

3、符合协议

该类实现了firstMethod 和secondMethod 方法,符合MyProtocol

@interface MyClassController : UIViewController <MyProtocol> {

MyClass *myClass;

}

@property [retain, nonatomic] MyClass *myClass;

@end

必须在该类的实现文件中,实现firstMethod 和 secondMethod方法,否则编译器会给出警告。

然后,通过如下代码设置代理:

self.myClass = [[MyClass alloc] init];

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