OC_协议实现代理委托模式

来源:互联网 发布:竖琴 踏板 知乎 编辑:程序博客网 时间:2024/05/01 11:23

例题

CareBabyProtocol.h文件

//协议文件import <Foundation/Foundation.h>@class Baby;@protocol CareBabyProtocol <NSObject>//协议中的方法-(void)babyDontClean:(Baby *)baby;@end

Baby.h文件

import <Foundation/Foundation.h>import "CareBabyProtocol.h"@interface Baby : NSObject//baby的清洁值属性@property(nonatomic,assign)NSInteger cleanValue;//baby中的代理者属性@property(nonatomic,weak)id<CareBabyProtocol> delegate;//重写init方法-(instancetype)init;@end

Baby.m文件

import "Baby.h"@implementation Baby-(instancetype)init{    if(self=[super init]){        //为cleanValue属性赋初始值        _cleanValue=100;        //创建一个定时器        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(observeCleanValue) userInfo:nil repeats:YES];    }    return self;}//定时器不断调用的方法-(void)observeCleanValue{    //清洁值每次减1    _cleanValue--;    if([_delegate respondsToSelector:@selector(babyDontClean:)]   &&[_delegate conformsToProtocol:@protocol(CareBabyProtocol)]){        //调用代理的方法        [_delegate babyDontClean:self];    }}@end

Nanny.h文件

import <Foundation/Foundation.h>import "CareBabyProtocol.h"//保姆实现照顾小孩的协议@interface Nanny : NSObject <CareBabyProtocol>//保姆的属性:小孩@property(nonatomic,strong)Baby *baby;@end

Nanny.m文件

import "Nanny.h"import "Baby.h"@implementation Nanny//保姆实现协议中的方法-(void)babyDontClean:(Baby *)baby{    NSInteger cleanValue=baby.cleanValue;    //保姆监视小孩的清洁值    NSLog(@"baby的清洁值为:%ld",cleanValue);    //当小孩的清洁值低于95时为小孩洗澡,恢复清洁值    if(cleanValue<95){        NSLog(@"保姆为baby洗澡了");        baby.cleanValue=100;    }}@end

运行结果:

结果图

0 0
原创粉丝点击