下面實現代碼!
#import <Foundation/Foundation.h>
#import "protocoldemo.h"
#import "Children.h"
#import "Jones.h"
int main(int argc, const char * argv[]) {
//初始化對象
Jones *jones = [[Jones alloc] init];
//創建對象 叫Jones去爲這個小孩服務
Children *children = [[Children alloc] initChildren:jones];
//設置小孩
[jones setChidren:children];
[[NSRunLoop currentRunLoop] run];
return 0;
}
//主協議
@protocol protocoldemo <NSObject>
@required
//照護小孩清潔方法
-(void)ChildClean;
//招呼小孩高興方法
-(void)lowHappy;
@end
#import <Foundation/Foundation.h>
#import "protocoldemo.h"
@interface Children : NSObject
//設置代理對象 不管是那個對象 要想照護小孩必須實現這個協議!
@property(nonatomic,retain) id<protocoldemo> delegate;
//高興
@property(nonatomic,assign) int happy;
//清潔
@property(nonatomic,assign) int clean;
//初始化對象的時候傳入實現這個協議的對象
-(instancetype)initChildren:(id<protocoldemo>) delegate;
-(void)ActionInit:(NSTimer*)timer;
@end
#import "Children.h"
@implementation Children
//初始化對象
-(instancetype)initChildren:(id<protocoldemo>)delegate
{
if (self = [super init])
{
self->_delegate = delegate;
self->_clean = 100;
self->_happy = 100;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ActionInit:) userInfo:nil repeats:true];
};
return self;
};
-(void)ActionInit:(NSTimer *)timer
{
self->_happy--;
self->_clean--;
if(self->_happy <= 90)
{
//小孩不高興了
[self->_delegate lowHappy];
};
if (self->_clean <=85) {
//小孩需要清理了
[self->_delegate ChildClean];
}
NSLog(@"高興值%d",_happy);
NSLog(@"清潔值%d",_clean);
};
#import <Foundation/Foundation.h>
#import "protocoldemo.h"
#import "Children.h"
//實現照護小孩的方法
@interface Jones : NSObject <protocoldemo>
//創建對象屬性
@property(nonatomic,retain) Children *chidren;
@end
#import "Jones.h"
@implementation Jones
-(void)ChildClean
{
NSLog(@"小孩清潔了");
self->_chidren.clean = 100;
}
-(void)lowHappy
{
NSLog(@"小孩高新了");
self->_chidren.happy = 100;
}
@end