iOS 的代理模式讨论
今天仔细研究了下代理模式,之前是只会用,不知道具体实现,更不会自己编写。
废话不多说,上代码!
1.拟定一份协议
//
// AssistantDelegate.h
// 141018Test
//
// Created by JieLee on 10/18/14.
// Copyright (c) 2014 PUPBOSS. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol AssistantDelegate <NSObject>
- (void)heisthirsty;
- (void)heishungry;
@end
2.编写需要代理的类 (要有代理的成员变量)
.h文件
//
// Professor.h
// 141018Test
//
// Created by JieLee on 10/18/14.
// Copyright (c) 2014 PUPBOSS. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AssistantDelegate.h"
@interface Professor : NSObject
@property (nonatomic, weak) id<AssistantDelegate> assis;
- (void)thirsty;
- (void)hungry;
@end
.m文件
//
// Professor.m
// 141018Test
//
// Created by JieLee on 10/18/14.
// Copyright (c) 2014 PUPBOSS. All rights reserved.
//
#import "Professor.h"
@implementation Professor
- (void)thirsty {
NSLog(@"i am thirsty");
[_assis heisthirsty];
}
- (void)hungry {
NSLog(@"i am hungry");
[_assis heishungry];
}
@end
3.编写实现代理的类 (要遵守代理协议)
.h文件
//
// Assistant.h
// 141018Test
//
// Created by JieLee on 10/18/14.
// Copyright (c) 2014 PUPBOSS. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AssistantDelegate.h"
@interface Assistant : NSObject <AssistantDelegate>
@end
.m文件
//
// Assistant.m
// 141018Test
//
// Created by JieLee on 10/18/14.
// Copyright (c) 2014 PUPBOSS. All rights reserved.
//
#import "Assistant.h"
@implementation Assistant
- (void)heishungry {
NSLog(@"give you food");
}
- (void)heisthirsty {
NSLog(@"give you water");
}
@end
4.编写main函数
//
// main.m
// 141018Test
//
// Created by JieLee on 10/18/14.
// Copyright (c) 2014 PUPBOSS. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Professor.h"
#import "Assistant.h"
int main(int argc, const char * argv[]) {
Professor *p = [Professor new];
p.assis = [Assistant new];
[p hungry];
[p thirsty];
return 0;
}
5.运行结果
2014-10-19 00:07:33.328 141018Test[2527:90902] i am hungry
2014-10-19 00:07:33.330 141018Test[2527:90902] give you food
2014-10-19 00:07:33.330 141018Test[2527:90902] i am thirsty
2014-10-19 00:07:33.330 141018Test[2527:90902] give you water
Program ended with exit code: 0
即使删除了 Assistant 这个类,程序也不会报错。
方法名上面可以加 @required
和 @optional
来修饰。
举个栗子:
@protocol AssistantDelegate <NSObject>
@required //必须实现的方法
- (void)heisthirsty;
@optional //可选实现的方法
- (void)heishungry;
@end
请注意 不声明的话默认是 @required 但是 编译不会报错,因为 Obj-C 是弱语法
不过问题就来了,这样做岂不是特别耗性能?不管代理有没有实现方法,都会通知代理做这件事情。