自定义NSOperation

2017-05-10  本文已影响17人  c048e8b8e3d7

一 简单的使用

如果只是简单地使用NSOperation,只需要重载main这个方法,在这个方法里面添加需要执行的操作

取消事件

DownloadOperation.h

@protocol DownloadOperationDelegate;

@interface DownloadOperation : NSOperation
@property(nonatomic, copy) NSString *imageUrl;
@property(nonatomic, assign) id<DownloadOperationDelegate> delegate;
- (instancetype)initWithURL:(NSString *)url
                   delegate:(id<DownloadOperationDelegate>)delegate;
@end

@protocol DownloadOperationDelegate <NSObject>
//这个方法不规范,这么写只是为了方便
- (void)downloadFinishedWithImage:(UIImage *)image;
@end

DownloadOperation.m

@implementation DownloadOperation

- (instancetype)initWithURL:(NSString *)url delegate:(id<DownloadOperationDelegate>)delegate
{
    if (self = [super init]) {
        _imageUrl = url;
        _delegate = delegate;
    }
    
    return self;
}

- (void)main
{
    @autoreleasepool {
        
        NSLog(@"Thread : %@", [NSThread currentThread]);
        //经常检测isCancelled属性,NSOperation可能会被cancel掉
        if (self.isCancelled) return;
        
        NSURL *url = [NSURL URLWithString:self.imageUrl];
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        if (self.isCancelled) return;
        
        UIImage *image = [UIImage imageWithData:data];
        
        if (self.isCancelled) return;
        
        if ([self.delegate respondsToSelector:@selector(downloadFinishedWithImage:)]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.delegate downloadFinishedWithImage:image];
            });
        }
    }
}

@end

使用

- (void)OPERATION06
{
    DownloadOperation *op1 = [[DownloadOperation alloc] initWithURL:@"http://i1.hoopchina.com.cn/u/1705/08/144/1144/414d5be1" delegate:self];
    
    DownloadOperation *op2 = [[DownloadOperation alloc] initWithURL:@"http://i1.hoopchina.com.cn/u/1705/08/144/1144/2241e6c1" delegate:self];
    
    NSOperationQueue *queue = [NSOperationQueue new];
    
    [queue addOperations:@[op1, op2] waitUntilFinished:NO];
    
//    [op2 cancel];
}

- (void)downloadFinishedWithImage:(UIImage *)image
{
    NSLog(@"image.size %@", NSStringFromCGSize(image.size));
}
上一篇 下一篇

猜你喜欢

热点阅读