OC 고효율 52의 블록으로 소속 객체를 참조할 때 보존 루프가 나타나지 않도록 합니다.

2061 단어
#import <Foundation/Foundation.h>
typedef void (^EOCNetworkFetcherCompletionHandler)(NSData *data);

@interface EOCNetworkFetcher : NSObject
@property (nonatomic , strong , readonly) NSURL *url;
-(id)initWithURL:(NSURL *)url;
-(void)startWithCompletionHandler:(EOCNetworkFetcherCompletionHandler)completion;
@end

#import "EOCNetworkFetcher.h"
@interface EOCNetworkFetcher ()
@property (nonatomic , strong , readwrite) NSURL *url;
@property (nonatomic , copy)EOCNetworkFetcherCompletionHandler completionHandler;
@property (nonatomic , strong)NSData *downLoadedData;
@end


@implementation EOCNetworkFetcher
-(id)initWithURL:(NSURL *)url{
    if (self = [super init]){
        _url = url;
    }
    return self;
}

-(void)startWithCompletionHandler:(EOCNetworkFetcherCompletionHandler)completion{

    self.completionHandler = completion;
    //Start the request
    //When request is finished,p_requestCompleted is called;
}
-(void)p_requestCompleted{
    if (_completionHandler){
        _completionHandler(_downLoadedData);
    }
    self.completionHandler = nil;// , 
}

@end
#import <Foundation/Foundation.h>

@interface FetcherData : NSObject

@end

#import "FetcherData.h"
#import "EOCNetworkFetcher.h"
@implementation FetcherData
{
    EOCNetworkFetcher *_netWorkfetcher;
    NSData *_fetcherdData;
}
-(void)downloadData{
    //begin
    NSURL *url = [[NSURL alloc]initWithString:@"www.google.cn"];
    _netWorkfetcher = [[EOCNetworkFetcher alloc]initWithURL:url];
    
    [_netWorkfetcher startWithCompletionHandler:^(NSData *data) {
        NSLog(@"equest URL%@ finish", _netWorkfetcher.url);
        _fetcherdData = data;
    }];
    //end  
    
    // 
    NSURL *url2 = [[NSURL alloc]initWithString:@"www.huangshuxian.cn"];
    _netWorkfetcher = [[EOCNetworkFetcher alloc]initWithURL:url2];
    
    [_netWorkfetcher startWithCompletionHandler:^(NSData *data) {
        _fetcherdData = data;
        _netWorkfetcher = nil;
    }];
}
@end

좋은 웹페이지 즐겨찾기