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