当前位置: 代码迷 >> Iphone >> (转载)深入懂得iphone开发中的delegate
  详细解决方案

(转载)深入懂得iphone开发中的delegate

热度:91   发布时间:2016-04-25 06:40:29.0
(转载)深入理解iphone开发中的delegate

深入理解iphone开发中的delegate

?

转载自: http://blog.csdn.net/zhanglei5415/article/details/6133852

?

先举一个例子:

?

假如"我"的本职工作之一是“接电话”,但"我"发现太忙了或来电太杂了,于是我聘请一位"秘书"分担我“接电话”的工作,如果电话是老板打来的,就让“秘书”将电话转接给“我”。。。

那么,“我”就是A Object.??“秘书”就是"我"的“Delegate”。写成代码就是 --?? [我 setDelegate:秘书];

?

delegate的概念出现与mvc(model-view-controller),protocol,单线继承 密切相关

The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.

Cocoa中处理事件的方式有几种,其中一种是你可以重载类中的对应的事件处理方 法,比如MouseDown事件在NSResponse类中就被方法mouseDown:处理,所以所有继承自NSResponse的类都可以重载 mouseDown:方法来实现对MouseDown事件的处理。

另外一种处理方式就是使用Delegate,当一个对象接受到某个事件或者通知的时候, 会向它的Delegate对象查询它是否能够响应这个事件或者通知,如果可以这个对象就会给它的Delegate对象发送一个消息(执行一个方法调用)

?

?

协议 Protocol :

我说下我的理解。object-c 里没有多继承。那么又要避免做出一个对象什么都会(super class monster,huge ,super,waste)一个超能对象 本身是否定了面向对象的概念和真谛了。为了让代码更简洁,条理更清楚,可以将部分职责分离。

协议本身没有具体的实现。只规定了一些可以被其它类实现的接口。


@protocal UITextFieldDelegate-(BOOL) textFieldShouldReturn:(UITextField *) textField ;@end
?

?

delegate 总是被定义为 assign @property

@interface UITextField@property (assign) id<UITextFieldDelegate> delegate;@end
?

?

这样我们就在UITextField内部声明一个委托(delegate),那么就需要委托的代理实现UITextFieldDelegate 中约定的行为

// 首先, 在接口里边声明要使用谁的Delegate@interface delegateSampleViewController : UIViewController    <UITextFieldDelegate> {}@end // 然后在实现文件中初始化的时候, 设置Delegate为self(自己)@implementation delegateSampleViewController // ....    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];    textField.delegate = self;//设置当前的控制器为UITextField的代理,相当于注册(指定)代理人    [textField becomeFirstResponder];    [cell.contentView addSubview:textField];    [textField release];// .... } // 实现UITextFieldDelegate中约定的行为#pragma mark UITextFieldDelegate Method// called when 'return' key pressed. return NO to ignore.- (BOOL)textFieldShouldReturn:(UITextField *)textField {     [textField resignFirstResponder];    return YES;}
?

?

?

  相关解决方案