Delegate定義網絡
#import <Foundation/Foundation.h> @class ZYNetworkFetcher; @protocol ZYNetworkFetcherDelegate <NSObject> -(void)networkFetcher:(ZYNetworkFetcher *)networkfetcher didfinishWithData:(NSData *)data; @end @interface ZYNetworkFetcher : NSObject @property (nonatomic,weak) id< ZYNetworkFetcherDelegate> delegate; -(instance)initWithURL:(NSURL *)url; -(void)start; @end
Block定義fetch
#import <Foundation/Foundation.h> typedef void(^ZYNetworkFetcherCompletionHandle01)(NSData *data); typedef void(^ZYNetworkFetcherCompletionHandle02)(NSData *data, NSError *error); @interface ZYNetworkFetcher : NSObject -(instance)initWithURL:(NSURL *)url; -(void)startWithCompletionHandle1:(ZYNetworkFetcherCompletionHandle01)handle; -(void)startWithCompletionHandle2:(ZYNetworkFetcherCompletionHandle02)handle; @end
場景一google
在一個UIViewController中,存在2個UITable,那麼在protocol的方法實現中,須要經過if/else區分是哪個table,代碼就被拉得很長,若是用block替代方案,某個table直接在API方法中傳入對應的block便可。 atom
好處:使用block塊調用更方便,代碼更清晰且API更緊緻,block中還能捕獲變量,url
-(void)startMain { NSURL *url01 = [[NSURL alloc] initWithString:@"https://www.baidu.com"]; _obj01 = [[ZYNetworkFetcher alloc] initWithURL:url01]; _obj01.delegate = self; [_obj01 start]; NSURL *url02 = [[NSURL alloc] initWithString:@"https://www.google.com"]; _obj02 = [[ZYNetworkFetcher alloc] initWithURL:url02]; _obj02.delegate = self; [_obj02 start]; } -(void)networkFetcher:(ZYNetworkFetcher *)networkfetcher didfinishWithData:(NSData *)data { // 須要判斷是哪個對象的回調 if (networkfetcher == _obj01) { _objData01 = data; } else if(networkfetcher == _obj02){ _objData02 = data; } }
-(void)startMain { NSURL *url01 = [[NSURL alloc] initWithString:@"https://www.baidu.com"]; _obj01 = [[ZYNetworkFetcher alloc] initWithURL:url01]; [_obj01 startWithCompletionHandle1:^(NSData *data){ _objData01 = data; }]; NSURL *url02 = [[NSURL alloc] initWithString:@"https://www.google.com"]; _obj02 = [[ZYNetworkFetcher alloc] initWithURL:url02]; [_obj02 startWithCompletionHandle1:^(NSData *data){ _objData02 = data; }]; }
場景二spa
網絡請求響應有成功和失敗兩種結果,一個block就能完成對成功和失敗結果的處理。code
有考慮用2個block分別處理,但這樣不是最優。好比在處理響應成功的過程當中發現錯誤,就得用失敗的block處理,這時就會有重複性代碼。對象
-(void)startMain { NSURL *url01 = [[NSURL alloc] initWithString:@"https://www.baidu.com"]; _obj01 = [[ZYNetworkFetcher alloc] initWithURL:url01]; [_obj01 startWithCompletionHandle2:^(NSData *data, NSError *error){ if (error) { // ...... } else { // ...... } }]; NSURL *url02 = [[NSURL alloc] initWithString:@"https://www.google.com"]; _obj02 = [[ZYNetworkFetcher alloc] initWithURL:url02]; [_obj02 startWithCompletionHandle2:^(NSData *data, NSError *error){ if (error) { // ...... } else { // ...... } }]; }
場景三blog
在API中,添加queue參數,能夠將block回調任務提交到指定的queue。it
好處:方便調用者對block的調度