代理模式
1.一般把协议放在代理中(见Person.h)
2.接收的类型用id 并且服从协议(@property(nonatomic,assign)id <agentDelegate> delegate)
3.一定要确保对象实现了方法([self.delegate respondsToSelector:@selector(call:)])
Person.h
#import <Foundation/Foundation.h>
#import "Agent.h"
@interface Person : NSObject <agentDelegate>
-(void)needHouse;
-(void)call:(NSString *)message;
@end
Person.m
#import "Person.h"
#import "Agent.h"
@implementation Person
-(void)needHouse{
Agent * ag = [[Agent alloc]init];
ag.delegate = self;
[ag rentHouse];
}
-(void)call:(NSString *)message{
NSLog(@"%@",message);
}
@end
Agent.h
@protocol agentDelegate <NSObject>
@optional
-(void)call:(NSString*)message;
@end
@interface Agent : NSObject
@property(nonatomic,assign)id <agentDelegate> delegate;
-(void)rentHouse;
@end
Agent.m
@implementation Agent
-(void)rentHouse{
NSLog(@"正在租房子");
if ([self.delegate respondsToSelector:@selector(call:)]){
[self.delegate call:@"租到房子了"];
}
}
@end