如何理解 Objective-C Delegate

例如,我们要在一个 ViewController 中使用一个ActionSheet,代码如下:

  UIActionSheet *actionSheet = [[UIActionSheet alloc]
          initWithTitle:@"Delegate Example"
          delegate:self // telling this class to implement UIActionSheetDelegate
          cancelButtonTitle:@"Cancel"
          destructiveButtonTitle:@"Destructive Button"
          otherButtonTitles:@"Other Button",nil

  [actionSheet showInView:self.view];

中间的代码: delegate:self 来告诉当前这个ViewController 来实现 UIActionSheetDelegate
这样做的原因是
ViewController 和 ActionSheet 二者是相互独立的,但是当用户点击了 ActionSheet 上的按钮时,ViewController 需要处理 ActionSheet 上按钮的点击事件,这样做相当于通知 ViewController 监听 UIActionSheetDelegate,以便我们处理 ActionSheet 上按钮的点击事件。

注意:
delegte:self; 这行代码仅是告诉 ViewController 实现 UIActionSheetDelegate,但是我们还需要告诉类实现 UIActionSheetDelegate protocol (协议),方法是在 .h 文件中 加入,如下所示:

@interface DelegateExampleViewController : UIViewController <UIActionSheetDelegate>
  • 我们自己创建的类 (CustomClass),如何使用 delegate

在CustomClass.h 文件中 首先要为这个 delegate 定义 protocol (写在 @interface 之前)
在 protocol 和 end 之间定义 protocol 方法, 这个方法可以被任何使用这个代理的类所使用

#import 
@class CustomClass;

//为Delegate 定义 protocol
@protocol CustomClassDelegate 
//定义 protocol 方法
-(void)sayHello:(CustomClass *)customClass;
@end

@interface CustomClass : NSObject {

}

// define delegate property
@property (nonatomic, assign) id  delegate;

// define public functions
-(void)helloDelegate;

@end

.m 文件中没什么特别的,最重要的要实现 helloDelegate 方法

-(void)helloDelegate {
    // send message the message to the delegate!
    [delegate sayHello:self];
}

接下来我们切换到要使用这个类的 ViewController ,实现上面刚刚创建的 delegate

// DelegateExampleViewController.h
// import our custom class

#import "CustomClass.h"

@interface DelegateExampleViewController : UIViewController <CustomClassDelegate> {

}
@end

在 DelegateExampleViewController.m 文件中,我们需要初始化这个 custom Class,然后让 delegate 给我们传递一条消息

//DelegateExampleViewController.m

CustomClass *custom = [[CustomClass alloc] init];

// assign delegate
custom.delegate = self;
[custom helloDelegate];

还是在 DelegateExampleViewController.m 我们要实现在 custom Class.h 中生命的 delegate function

-(void)sayHello:(CustomClass *)customClass {
    NSLog(@"Hi!");
}

Bingo!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值