iOS 代理模式

2017-03-02  本文已影响45人  印林泉

委托方(老板)

//
//  Boss.h
//  LearnDelegate
//
//  Created by 印林泉 on 2017/3/2.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol BossDelegate <NSObject>

- (void)buyWood;

@end

@interface Boss : NSObject

@property (nonatomic, strong) id<BossDelegate> delegate;

- (void)sendCommand;

@end
//
//  Boss.m
//  LearnDelegate
//
//  Created by 印林泉 on 2017/3/2.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "Boss.h"

@implementation Boss

- (void)sendCommand {
    NSLog(@"send command");
    [self.delegate buyWood];
}

@end

代理者(老王)

//
//  Worker.h
//  LearnDelegate
//
//  Created by 印林泉 on 2017/3/2.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Boss.h"

@interface Worker : NSObject<BossDelegate>

@end
//
//  Worker.m
//  LearnDelegate
//
//  Created by 印林泉 on 2017/3/2.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "Worker.h"

@implementation Worker

- (void)buyWood {
    NSLog(@"buy wood");
}
@end

设置代理(老板买木头)

//
//  ViewController.m
//  LearnDelegate
//
//  Created by 印林泉 on 2017/3/2.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "ViewController.h"
#import "Boss.h"
#import "Worker.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Worker *worker = [[Worker alloc] init];
    Boss *boss = [[Boss alloc] init];
    [boss setDelegate:worker];
    [boss sendCommand];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

不用关心代理者,遵守协议就与委托方建立关联。通过协议建立通信。

上一篇下一篇

猜你喜欢

热点阅读