#import <Foundation/Foundation.h>
@protocol Job <NSObject>
-(void)takeEat;
-(void)takeSleep;
-(void)takePlay;
-(void)takeShower;
@end
我们再声明Nurse类 即代理的人:
#import <Foundation/Foundation.h>
#import "Job.h"
@interface Nurse : NSObject<Job>//实现该协议
@end
实现文件:
#import "Nurse.h"
@implementation Nurse
-(void)takeEat
{
NSLog(@"小孩饿了,喂它吃饭");
}
-(void)takeSleep
{
NSLog(@"小孩困了,哄他睡觉");
}
-(void)takePlay
{
NSLog(@"小孩醒来了,陪他玩");
}
-(void)takeShower
{
NSLog(@"晚上给小孩洗澡");
}
-(void)dealloc
{
NSLog(@"Nurse is dealloc");
}
@end
再声明一个morther类:
#import <Foundation/Foundation.h>
#import "Job.h"
@class Nurse;
@interface Morther : NSObject
{
NSString *name;
id<Job> delegate; //此处声明一个代理人,从而mother可以让代理人完成需要代理的事情
}
-(id)initWithName:(NSString *)_name delagat:(id<Job>)_delagete; //传入代理人
@property(nonatomic,copy)NSString *name;
-(void)delagateThings;// 被代理的事情
@end
//实现文件
#import "Morther.h"
#import "Nurse.h"
@implementation Morther
-(id)initWithName:(NSString *)_name delagat:(id)_delagete
{
self=[super init];
if (self) {
if (name!=_name) {
[name release];
name=[_name copy];
[delegate release];
delegate=[_delagete retain];
}
}
return self;
}
@synthesize name;
-(void)dealloc
{
[name release];
[delegate release];
NSLog(@"host is dealloc");
}
-(void)delagateThings
{
int i;
switch (i) {
case 1:
[delegate takeEat];
break;
case 2:
[delegate takePlay];
break;
case 3:
[delegate takeShower];
break;
case 4:
[delegate takeSleep];
break;
default:
break;
}
i++;
}
@end
看看 在 main 文件中是怎么实现的:
#import <Foundation/Foundation.h>
#import "Morther.h"
#import "Nurse.h"
#import "Job.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSString *name=[[NSString alloc] initWithFormat:@"小花"];
Nurse *fengjie=[[Nurse alloc] init];//代理人 fengjie
Morther *morther=[[Morther alloc] initWithName:name delagat:fengjie];//这样就将代理人传入mother 对象中,这样morther对象便可以通过nurse来完成她自己不能坐的事情了。
[name release];
[NSTimer scheduledTimerWithTimeInterval:2 target:morther selector:@selector(delagateThings) userInfo:nilrepeats:YES]; //调用机制, 2秒调用一次, 调用的对象是morther , 调用的方法是delagateThings;
[[NSRunLoop currentRunLoop] run]; //让程序一直运行下去,保证上面的调用可以一直进行
[morther release];
[fengjie release];
}
return 0;
}
代理中,需要记住的关键是在发出代理请求的类(A)中声明代理人(B)的实例变量,这样就可以保证A 能通过调用B中B代理的方法来完成B代理的事情,即自己代理给B 的事情。