iOS 开发学习之 delegate

概述

本节内容要求读者对设计模式有一定的了解。


在《iPhone 3 开发基础教程》的4.7节,讲述了如何实现操作表和警告,这里使用了 delegate,一个新的名词,这东西到底是个啥?在网上搜索了一些资料,看的我还是云遮雾绕的。最后,还是 Apple 的 iOS Developer Library 给力。

首先来看看这个 delegate 是如何引入的。

4.7 节这里要实现操作表和警报,我们忽略后者,单看操作表。这里就要用到 delegate,先不管它是什么,我们只看是如何做的:

1、为了让控制器充当操作表的委托,控制器类要遵从 UIActionSheetDelegate 协议。

#import <UIKit/UIKit.h>
@define kSwitchesSegmentIndex 0
@interface Control_FunViewController : UIViewController<UIActionSheetDelegate> {
    ...
}


2、显示操作表

- (IBAction) buttonPressed {
    // TODO: Implement Action Sheet and Alert
    UIActionSheet *actionSheet = [[UIActionSheet alloc] 
                         initWithTitle:@"..." 
                         delegate:self // 设置委托
                         cancelButtonTitle:@"..." 
                         destructiveButtonTitle:@"..."
                         otherButtonTitles:nil];
    [actionSheet showInView:self.view];
    [actionSheet release];
}

3、实现 UIActionSheetDelegate 中的 actionSheet 方法

- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    ...
}

好了,到这里,代码就写完了,但么 delegate 是如何工作的呢?

buttonPressed 方法在视图中按钮被按下时调用

然后将显示这个 ActionSheet

在创建 ActionSheet 时我们将 delegate 设置为了 self,所以,对这个 ActionSheet 做的操作都会委托给实现了 UIActionSheetDelegate 的 FunViewController 来完成

我们在 FunViewController 中实现的 actionSheet 将覆盖 UIActionSheetDelegate 中对应的方法

这就是委托的工作方式,看起来真像是设计模式里的策略模式(strategy)啊,到底是不是呢?我们接着分析。


查看 iOS Developer Library,找到关于 UIActionSheet 和 UIActionSheetDelegate 的 Reference,在 UIActionSheet 中我们看到 delegate 的定义如下:

delegate

The receiver’s delegate or nil if it doesn’t have a delegate. @property(nonatomic, assign) id<UIActionSheetDelegate> delegate Discussion For a list of methods your delegate object can implement, see UIActionSheetDelegate Protocol Reference. Availability Available in iOS 2.0 and later. Declared In UIActionSheet.h


这里 delegate 的类型是 id<UIActionSheetDelegate>,它要求 delegate 指向的对象必须是实现了 UIActionSheetDelegate 协议(Protocol)的。这很像泛型。


这么看来,其实 delegate 就是设计模式中 strategy (策略)模式的实现。

我们先来看一下什么是策略模式:针对一组算法,将每一个算法具有共同接口的独立类中,从而使它们可以互相替换。

称之为 delegate 还是 strategy 并没有什么特别的,本质不变。



后记

初学 iOS 开发就碰到这么个东西,网上对其解释又不是很清晰(也许我没找到),经过上面的分析, delegate 也就清晰了,至于还有没有其它的解释,随着学习的深入,我们后面再说。


参考:

1、UIAlertViewDelegate Protocol Reference

2、UIActionSheet Class Reference

3、《Java与模式》

4、objective-C中的接口与泛型

5、

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值