美文网首页
自定义NSOperation

自定义NSOperation

作者: c048e8b8e3d7 | 来源:发表于2017-05-10 11:26 被阅读17次

一 简单的使用

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

取消事件
  • 默认情况下,一个NSOperation开始执行之后,会一直执行任务到结束,就比如下面的DownloadOperation,默认会执行完main方法中的所有代码。

  • NSOperation提供了一个cancel方法,可以取消当前的操作。

  • 如果是自定义NSOperation的话,需要手动处理这个取消事件。比如,一旦调用了cancel方法,应该马上终止main方法的执行,并及时回收一些资源。

  • 处理取消事件的具体做法是:在main方法中定期地调用isCancelled属性检测操作是否已经被取消,也就是说是否调用了cancel方法,如果返回YES,表示已取消,则立即让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));
}

相关文章

网友评论

      本文标题:自定义NSOperation

      本文链接:https://www.haomeiwen.com/subject/sngwtxtx.html