OC高效率52之用塊引用其所屬對象時不要出現保留環

#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
相關文章
相關標籤/搜索