//
// main.m
// 委托(代理)
//
// Created by on 14-10-7.
// Copyright (c) 2014年 apple. All rights reserved.
//
#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" withDelegate:agent];
[jack wantToFindApartment];
// 因为这里是命令行演示,所以用NSRunLoop让当前线程不断地执行模拟设备,才能输出内容,
// 否则程序直接return掉,没有输出。
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
//
// Person.h
// 委托(代理)
//
// Created by on 14-10-7.
// Copyright (c) 2014年 apple. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FindApartment.h"
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
// 这里设置assign,方式程序重复引用
// <FindApartment>表示delegate具有FindApartment的能力
@property (nonatomic, assign) id <FindApartment> delegate;
- (id) initWithName:(NSString *)_name withDelegate:(id <FindApartment>) _delegate;
- (void) wantToFindApartment;
@end
//
// Person.m
// 委托(代理)
//
// Created by on 14-10-7.
// Copyright (c) 2014年 apple. All rights reserved.
//
#import "Person.h"
@interface Person ()
- (void)startFindApartment:(NSTimer *)timer;
@end
@implementation Person
@synthesize name;
@synthesize delegate;
- (id) initWithName:(NSString *)_name withDelegate:(id <FindApartment>) _delegate {
if (self = [super init]) {
self.name = _name;
self.delegate = _delegate; // 设置代理
}
return self;
}
- (void) wantToFindApartment {
// 调用机制
// 2秒调用一次,调用对象是self(如果写在main文件中调用对象就应该写成Person类的对象jack),
// 调用方法是startFindApartment
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startFindApartment:) userInfo:@"user info" repeats:YES];
}
- (void)startFindApartment:(NSTimer *)timer {
[self.delegate findApartment];
}
@end
//
// Agent.h
// 委托(代理)
//
// Created by on 14-10-7.
// Copyright (c) 2014年 apple. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FindApartment.h"
@interface Agent : NSObject <FindApartment>
@end
//
// Agent.m
// 委托(代理)
//
// Created by on 14-10-7.
// Copyright (c) 2014年 apple. All rights reserved.
//
#import "Agent.h"
@implementation Agent
- (void)findApartment {
NSLog(@"find");
}
@end
//
// FindApartment.h
// 委托(代理)
//
// Created by on 14-10-7.
// Copyright (c) 2014年 apple. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol FindApartment <NSObject>
- (void) findApartment;
@end