iOS 代理模式

  • 代理模式
    确定委托方和代理者。由委托方制定协议、规范接口。让任意类型的遵守协议的代理方设置为委托方需要的代理者,代理方遵守协议、实现协议方法。委托方正确地设置代理,建立委托方和代理者关联。委托方决定代理调用某个方法的时机。

  • 应用,适用场景
    老板叫老王买木头。

委托方(老板)

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 委托(代理)模式在iOS应用中可谓"遍地开花",不仅在我们的应用中会大量的使用它,即便是在Cocoa Touch框...
    尘絮缘12138阅读 1,393评论 0 6
  • 在iOS开发中代理是非常常见和普遍的,代理是一种通用的设计模式,iOS中对代理支持的很好,由代理对象、委托者、协议...
    高级搬砖工阅读 4,315评论 5 7
  • 第一步:定义协议 @protocol ModelDelegate -(void)letModelDoSomethi...
    RunnerFL阅读 456评论 0 1
  • iOS中消息传递方式 在iOS中有很多种消息传递方式,这里先简单介绍一下各种消息传递方式。 通知:在iOS中由通知...
    GitHubPorter阅读 1,674评论 0 5
  • 寒假回家,大事没有,零零碎碎的事情不少,眨眼间就是假期的末尾了。 妹妹已经开学好几天了,弟弟还有一周多的时间也要开...
    徐一朵儿阅读 122评论 0 0