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


//就是這樣吧,完。

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