iOS 开发学习之 delegate

来源:互联网 发布:新人淘宝刷単教程 编辑:程序博客网 时间:2024/04/30 04:00

概述

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


在《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> delegateDiscussionFor a list of methods your delegate object can implement, see UIActionSheetDelegate Protocol Reference.AvailabilityAvailable in iOS 2.0 and later.Declared InUIActionSheet.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、

原创粉丝点击