通过中介公司找房子
//1:协议声明: #import <Foundation/Foundation.h> @protocol FindApartment <NSObject>
-(void)findApartment; @end //2:代理角色声明(Agent.h)头文件声明 #import <Foundation/Foundation.h> #import "FindApartment.h" @interface Agent : NSObject <FindApartment> @end //3:代理角色实现(Agent.m)实现文件 #import "Agent.h" @implementation Agent -(void)findApartment{ NSLog(@"findApartment"); } @end //4:真实角色声明(Person.h)头文件声明 #import <Foundation/Foundation.h> #import "FindApartment.h" @interface Person : NSObject { @private NSString *_name; id<FindApartment> _delegate; //委托人(具备中介找房子的协议) } @property(nonatomic,copy) NSString *name; @property(nonatomic,assign)id<FindApartment> delegate; -(id)initWithName:(NSString *)name withDelegate:(id<FindApartment>) delegate; -(void)wantToFindApartment; @end //5:真实角色实现(Person.m)实现 #import "Person.h" //定义私有方法 @interface Person() -(void)startFindApartment:(NSTimer *)timer; @end @implementation Person @synthesize name=_name; @synthesize delegate=_delegate; -(id)initWithName:(NSString *)name withDelegate:(id<FindApartment>) delegate{ self=[super init]; if(self){ self.name=name; self.delegate=delegate; } return self; } -(void)wantToFindApartment{ [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startFindApartment:) userInfo:@"Hello" repeats:YES]; } -(void)startFindApartment:(NSTimer *)timer{ //NSString *userInfo=[timer userInfo]; [self.delegate findApartment]; } @end //6:测试代理main.m方法 #import <Foundation/Foundation.h> #import "Person.h" #import "Agent.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); Agent *agent=[[Agent alloc]init]; Person *jack=[[Person alloc]initWithName:@"jack" withDelegate:agent]; [jack wantToFindApartment]; [[NSRunLoop currentRunLoop]run]; [jack autorelease]; }
return 0; }
原文:http://www.cnblogs.com/KeenLeung/p/5016895.html