Objective-C 代理的例子

来源:互联网 发布:iptables内网端口转发 编辑:程序博客网 时间:2024/06/03 16:39

假设有一个Jack的人(Person),他想租一套公寓(Apartment),由于他工作繁忙,没有时间去租房,因此,他委托中介(Agent)帮他寻找房源,找到合适的房源告知Jack。

首先创建一个Person类(写出基本属性和方法),person需要找房子,但是自己工作繁忙做不了,需要去找一个代理,因此一般就在这个类中写协议方法。然后代理人Agent遵守协议并实现协议中必须要实现的方法。然后再行完善,最后main文件里实现就可以了。

Person.h:

#import <Foundation/Foundation.h>typedef enum {    kHighRent,    kLowRent,    kMiddleRent,}HouseRent;@class Person;@protocol LookingForApartment <NSObject>-(HouseRent) findApartment:(Person *) person;@end@interface Person : NSObject@property (nonatomic,copy) NSString *name;@property (nonatomic,assign) id<LookingForApartment> delegate; //代理,委托对象-(id) initWithName: (NSString *) name andDelegate: (id<LookingForApartment>) delegate;-(void) wantToFindApartment;-(void) startToFindApartment:(NSTimer *)timer;@end
Person.m:

#import "Person.h"int count = 0;@implementation Person-(id) initWithName:(NSString *)name andDelegate:(id<LookingForApartment>)delegate{    self = [super init];    if ( self ) {        self.name = name;        self.delegate = delegate;    }        return self;}-(void) startToFindApartment:(NSTimer *)timer{    HouseRent rent = 0;    //安全判断,加一层保护,增加代码健壮型    if ( [_delegate respondsToSelector:@selector(findApartment:)] ) {        rent = [_delegate findApartment:self];    }        if ( rent == kHighRent ) {        NSLog(@"价格太高,不要这套");    }else if ( rent == kLowRent ) {        NSLog(@"价格虽然低,但条件不太好");    }else {        NSLog(@"价格刚好,环境不错,就要这套了");        [timer invalidate];    }        count++;}-(void) wantToFindApartment{    //创建一个定时器    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startToFindApartment:) userInfo:nil repeats:YES];}@end


Agent.h:

#import <Foundation/Foundation.h>#import "Person.h"@interface Agent : NSObject <LookingForApartment>@end

Agent.m:

#import "Agent.h"extern int count;@implementation Agent#pragma mark LookingForApartment-(HouseRent) findApartment:(Person *)person{    HouseRent rent;    if ( count == 0 ) {        rent = kHighRent;    }else if ( count == 1 ) {        rent = kLowRent;    }else {        rent = kMiddleRent;    }        return rent;}@end

main.m:
#import <Foundation/Foundation.h>#import "Person.h"#import "Agent.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        Agent *agent = [[Agent alloc] init];        Person *jack = [[Person alloc] initWithName:@"Jack"andDelegate:agent];                [jack wantToFindApartment];                [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:8]];    }    return 0;}


0 0
原创粉丝点击