您的位置:首页 > 其它

我的OC练习(六)- 协议与代理

2015-11-11 00:14 453 查看
先上代码:

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


这是入学测试题中的一道。我以此为例,学习并实践了协议和代理的使用。还是很方便很好用的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: