我的OC练习(六)- 协议与代理
2015-11-11 00:14
453 查看
先上代码:
main.m
AsistPro.h
Baby.h
Baby.m
Baomu.h
Baomu.m
这是入学测试题中的一道。我以此为例,学习并实践了协议和代理的使用。还是很方便很好用的。
main.m
// // main.m // 5th // // Created by Morning on 2015/11/10. // Copyright © 2015年 Morning. All rights reserved. // #import <Foundation/Foundation.h> #import "Baomu.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... Baby* baby1=[Baby new]; Baomu* bm=[Baomu new]; baby1.delegate=bm;//将babay的代理设为bm。 baby1.name=@"sure"; [baby1 cry]; } return 0; }
AsistPro.h
// // Header.h // 1st // // Created by Morning on 2015/11/10. // Copyright © 2015年 Morning. All rights reserved. // #import <Foundation/Foundation.h> @class Baby; @protocol AsistPro <NSObject>//创建一个协议 @required -(void)dealWithCrying:(Baby*)baby;//必须实现的方法 @end
Baby.h
// // Baby.h // 1st // // Created by Morning on 2015/11/10. // Copyright © 2015年 Morning. All rights reserved. // #import <Foundation/Foundation.h> #import "AsisitPro.h" @interface Baby : NSObject @property BOOL iscrying; @property NSString* name; @property id<AsistPro> delegate;//申明一个指针指向遵守AsisPro协议的对象 -(void)cry; @end
Baby.m
// // Baby.m // 1st // // Created by Morning on 2015/11/10. // Copyright © 2015年 Morning. All rights reserved. // #import "Baby.h" @implementation Baby //@synthesize iscrying=_iscrying -(void)cry{//方法哭的实现 _iscrying=YES; if([self.delegate respondsToSelector:@selector(dealWithCrying:)]){//检查代理是否含有dealWithCrying方法 [self.delegate dealWithCrying:self];//调用代理的dealWithVCrying方法 } } @end
Baomu.h
// // Baomu.h // 1st // // Created by Morning on 2015/11/10. // Copyright © 2015年 Morning. All rights reserved. // #import <Foundation/Foundation.h> #import "AsisitPro.h" #import "Baby.h" @interface Baomu : NSObject <AsistPro>//申明类遵守AsistPro协议 @end
Baomu.m
// // Baomu.m // 1st // // Created by Morning on 2015/11/10. // Copyright © 2015年 Morning. All rights reserved. // #import "Baomu.h" @implementation Baomu -(void)dealWithCrying:(Baby *)baby{//实现协议@required的方法 baby.iscrying=NO; NSLog(@"Baby %@'s crying stoped!",baby.name); } @end
这是入学测试题中的一道。我以此为例,学习并实践了协议和代理的使用。还是很方便很好用的。
相关文章推荐
- 反转二进制数输出十进制值
- select poll epoll iocp kqueue
- 我的工作之旅
- zzuli OJ 1117: 查找数组元素
- c++中将文件内容清空
- 在frame中访问父窗口中的变量时,无法访问
- C#App.config的使用
- 近日工作小结_2015年11月11日0:10:48
- 程显峰:保障双11不掉“底裤”的5种安全武器
- Hibernate一级和二级缓存
- Home Server
- Home Server
- Android Studio用patch更新方法
- ARM的位置无关程序设计
- Python 一篇学会多线程
- 单一职责原则
- UVA 10256 (计算几何 凸包)
- 栈堆
- 开发小技巧-移除mysql服务
- call/apply/bind 的理解与实例分享