好久沒寫blog了~ 今天有同學問delegate的使用,順便寫點東西。
ios 的 delegate經常出現在 model 與 controller之間的通信。delegate中文叫做委托,就是委托別人幫你完成的意思。比如 我寫了個interface,服務器返給我我要的數據,同時告訴我success,那么我在controller怎么接收到這個interface的信息呢。 我的實現是這樣子的:在interface中寫一個delegate,(這個delegate 可以直接繼承自 Objective - C protocol,也可以直接寫在其他的類里面),讓返回成功和失敗時執行 delegate的方法,在controller中實現這些方法。
由於網絡接口都是公司的網址,不方便。所以簡單的寫個示意程序:
@protocol BaseInterfaceDelegate <NSObject>
@required//必須實現的代理方法
-(void)parseResult:(ASIFormDataRequest *)request;
-(void)requestIsFailed:(NSError *)error;
@optional//不必須實現的代理方法
@end
@interface BaseInterface : NSObject <DefaultLoginInterfaceDelegate,ASIHTTPRequestDelegate> {
ASIFormDataRequest *_request;
}
@property (nonatomic,assign) id<BaseInterfaceDelegate> baseDelegate; //一般delegate都是assign的防止循環circular count產生。
-(void)connect;
@end
@implementation BaseInterface
@synthesize baseDelegate = _baseDelegate;
-(void)connect {
寫網絡請求
}
#pragma mark - ASIHttpRequestDelegate//網絡情求的代理ASIHttpRequestDelegate
-(void)requestFinished:(ASIFormDataRequest *)request {
[_baseDelegate parseResult:request];//用實例變量delegate執行代理方法 表示一旦返回成功就執行這個方法,而這個方法究竟執行什么操作,就需要建立這個類對像的controller去實現。
}
-(void)requestFailed:(ASIFormDataRequest *)request {
[_baseDelegate requestIsFailed:request.error];//用實例變量delegate執行代理方法 表示一旦返回失敗就執行這個方法,而這個方法究竟執行什么操作,就需要建立這個類對像的controller去實現。
}
@interface MyController:UIViewController <DefaultLoginInterfaceDelegate> {
BaseInterface *interface;
}
@implementation MyController;
這個類中的其他方法省略,只寫delegate方法
//對delegate方法的實現
-(void)parseResult:(ASIFormDataRequest *)request
{
對返回的 request做相應的操作,並對界面做相應的操作。
}
-(void)requestIsFailed:(NSError *)error
{
對返回的 error做相應的操作,並對界面做相應的操作。
}
-(void)dealloc
{
self.delegate = nil;//防止delegate在這個類生命周期結束后還在對僵屍進行操作。
}