Object-C代码练习【委托(代理)视频学习】

//
//  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

转载于:https://my.oschina.net/are1OfBlog/blog/332794

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值