iOS 代理

 https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html

官方文档第一段原文:

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object. 

简单总结下自己的经验。若发现错误,请及时告知。

代理,字面意思:代替,替代,代表处理。

在这里,就是一个对象代替另一个对象,完成某项任务,并同时遵守共同的约定。

举例:A、B两个类。 B代理A ,完成某个任务。

代码要点如下:

AClass.h中,

#import "Foundation.h"

@protocal ABDelegate;

@interface:Aclass:NSObject {

id<ABDelegate>  *delegate;

//其他成员变量......

}

@property(nonatomic,assign) id <ABDelegate> delegate;

//其他属性,方法.......

@end


@protocol ABDelegate

- (void) DoSomething;

@end


AClasss.m 中

#import "AClass.h"

@implemetation AClass

@sythnsize delegate;

//其他代码......

@end


BClass.h 中

#improt "Foundation.h"

#improt "AClass.h"

@Class BClass :NSObject <ABDelegate> {

}

@end


BClass.m中

#improt "BClass.h"

@implemetation BClass

//....其他属性,方法

-(void)ViewDidLoad {

[super ViewDidload];

AClass * a = [[AClass alloc]init] ;

a.delegate = self ;

}

//.........

- (void)DoSomething {

 //进行任务动作......

}

@end


//就是这样吧,完。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值