OC高效率52之用handler塊下降代碼分散程度

#import <Foundation/Foundation.h>
@class EOCNetworkFetworkFetcher;
@protocol EOCNetworkFetworkFetcherDelegate <NSObject>

-(void)networkFetcher:(EOCNetworkFetworkFetcher *)networkFetcher didFinishWithData:(NSData *)data;

@end

/**
 *  block替換協議
 */
typedef void (^EOCNetworkFetcherCompletionHandler)(NSData *data);

typedef void (^EOCNetworkFetcherCompletionHandlerSuccessAndFail)(NSData *data,NSError *error);
@interface EOCNetworkFetworkFetcher : NSObject
@property (nonatomic , weak) id<EOCNetworkFetworkFetcherDelegate> delegate;
-(id)initWithURL:(NSURL *)url;

-(void) start;

-(void) startWithCompletionHandler:(EOCNetworkFetcherCompletionHandler) handler;

-(void) startWithCompletionHandlerSuccessAndFail:(EOCNetworkFetcherCompletionHandlerSuccessAndFail) complition;
@end

#import "EOCNetworkFetworkFetcher.h"

@implementation EOCNetworkFetworkFetcher

-(id)initWithURL:(NSURL *)url{
    EOCNetworkFetworkFetcher *fetch =[[EOCNetworkFetworkFetcher alloc]init];
    return fetch;
}

-(void)start{


}
@end


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@end

#import "ViewController.h"
#import "EOCNetworkFetworkFetcher.h"
@interface ViewController ()<EOCNetworkFetworkFetcherDelegate>
@property (nonatomic , strong)NSData *fetchData;
@property (nonatomic , strong)NSData *foofetcher;
@property (nonatomic , strong)NSData *barfetcher;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = [[NSURL alloc]initWithString:@"http://www.example.com/foo.dat"];
    EOCNetworkFetworkFetcher *fetcher = [[EOCNetworkFetworkFetcher alloc]initWithURL:url];
    fetcher.delegate = self;
    [fetcher start];
    
    /**
     *  block回調
     *
     *  @param data
     *
     *  @return 
     */
    [fetcher startWithCompletionHandler:^(NSData *data) {
        _fetchData = data;
    }];
    
    [fetcher startWithCompletionHandler:^(NSData *data) {
        _foofetcher = data;
    }];
    
    [fetcher startWithCompletionHandler:^(NSData *data) {
        _barfetcher = data;
    }];
    
    /**
     *  使用同一個塊來處理成功與失敗狀況
     */
    [fetcher startWithCompletionHandlerSuccessAndFail:^(NSData *data, NSError *error) {
        if (error){
        
        }else{
        
        }
        
    }];
    
    
   
}

-(void)networkFetcher:(EOCNetworkFetworkFetcher *)networkFetcher didFinishWithData:(NSData *)data{

    _fetchData = data;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
相關文章
相關標籤/搜索