ios编程思想:委托实现方式1 - 协议方式(protocol)

<<设计思想>>:

  • 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;
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值