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


//就是这样吧,完。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章