关于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;
它们包含一个方法列表,有些是必须被实现的,有些是可选的。
任何实现了必需方法的类都被认为符合协议。
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;
相关文章推荐
- [转载]关于Java reference的一篇博文
- 一篇关于GCC的转载的文章 很好。。。。
- 好东西,转载园子的博文。关于值类型和引用类型区别,讲的很清晰
- 转载一篇杨澜的演讲稿——关于孩子的想象力创造力
- 关于.net委托的一篇妙文
- 关于有限自动机的一篇不错的文章[转载]
- 转载 韩寒关于绿坝的博文
- 关于.net委托的一篇妙文[转]
- 关于指针常量和常量指针(本来想自己写的,发现自己有混淆了,因此转载了一篇)
- 一篇关于职业选择的好文章(转载)
- 很好的一篇关于C#事件与委托的文章
- 转载一篇过来人谈的大学期间关于课外学习的意见&lt;出自左飞老师笔记&gt;
- 一篇很好的关于 java@SuppressWarings注解的文章,转载自http://www.cnblogs.com/fsjohnhuang/p/4040785.html
- 转载一篇关于堆栈的好文章
- 转载一篇关于HTML5 data-* 自定义属性的文章
- 转载知乎一篇关于大数据生态技术的文章
- 转载一篇关于ALE的应用极好的文章
- 关于.net委托的一篇妙文
- 转载一篇关于移动端web常见问题解决方案
- 关于.net委托的一篇妙文作者: 周建东 日期: 2007-06-13 16:42