<<设计思想>>:
- MyClass是主类
- 当MyClass要打印时,委托DelegateClass执行打印
- 具体打印用到的方法,通过协议定义,该协议在DLogProtocol内声明
- 结构如下:
<具体实现>>:
一、通常在类的头文件内定义协议,也可以单独使用一个头文件定义协议
// DLogProtocol.h
// 定义打印用到的方法
@protocol DLogProtocol<NSObject>
@required
- (void)printLogs1;
@optional
- (void)printLogs2;
@end
二、定义一个委托类(遵循需要使用的协议),用于给别的类作为委托对象
// DelegateClass.h
#import "DLogProtocol.h" //-->需要导入协议的头文件
//该类遵循DLogProtocol协议,可以用来作为MyClass的委托对象
@interface DelegateClass : NSObject <DLogProtocol>
@end
// DelegateClass.m
// 实现具体的打印方法
@implementationDelegateClass
- (void)printLogs1 {
NSLog(@"printLogs1.....");
}
@end
三、在主类里面,需要定义一个id类型的属性,用于指定委托类对象。
// MyClass.h
// MyClass含有一个委托id属性,用于指定委托对象
@interface MyClass : NSObject
@property (nonatomic,strong)id<DLogProtocol>delegate;
- (void)helpMeToPrint;
@end
主类里面需要打印时(helpMeToPrint),交给delegate处理
// MyClass.m
@implementation MyClass
- (void)helpMeToPrint {
[self.delegateprintLogs1];
}
@end
四、最后,将id指向委托类,
// main.m
#import "MyClass.h"
#import "DelegateClass.h"
int main(intargc,const char* argv[]) {
@autoreleasepool {
MyClass *myclass = [[MyClassalloc]init];
DelegateClass *declass = [[DelegateClassalloc]init];
myclass.delegate = declass;
[myclass helpMeToPrint];
}
return 0;
}