下面实现代码!
#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
本文探讨了如何通过实现主协议、子类和定时器,使用Objective-C编程语言自动化照料儿童的过程,包括清洁和情绪调节。
235

被折叠的 条评论
为什么被折叠?



