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
運作結果: