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

先上代码:

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


这是入学测试题中的一道。我以此为例,学习并实践了协议和代理的使用。还是很方便很好用的。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值