iOS多线程应用开发中自定义NSOperation类的实例解析

2020-01-14 18:41:39于丽

1.通过代理

在上面的基础上,新建一个类,让其继承自NSOperation。

YYdownLoadOperation.h文件

复制代码
//
//  YYdownLoadOperation.h
//  01-自定义Operation
//
//  Created by apple on 14-6-26.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

 

#import <Foundation/Foundation.h>

#pragma mark-设置代理和代理方法
@class YYdownLoadOperation;
@protocol YYdownLoadOperationDelegate <NSObject>
-(void)downLoadOperation:(YYdownLoadOperation*)operation didFishedDownLoad:(UIImage *)image;
@end


复制代码
@interface YYdownLoadOperation : NSOperation
@property(nonatomic,copy)NSString *url;
@property(nonatomic,strong)NSIndexPath *indexPath;
@property(nonatomic,strong)id <YYdownLoadOperationDelegate> delegate;
@end
YYdownLoadOperation.m文件
复制代码
//
//  YYdownLoadOperation.m
//  01-自定义Operation
//
//  Created by apple on 14-6-26.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

 

#import "YYdownLoadOperation.h"

@implementation YYdownLoadOperation
-(void)main
{
    NSURL *url=[NSURL URLWithString:self.url];
    NSData *data=[NSData dataWithContentsOfURL:url];
    UIImage *imgae=[UIImage imageWithData:data];
    
    NSLog(@"--%@--",[NSThread currentThread]);
    //图片下载完毕后,通知代理
    if ([self.delegate respondsToSelector:@selector(downLoadOperation:didFishedDownLoad:)]) {
        dispatch_async(dispatch_get_main_queue(), ^{//回到主线程,传递数据给代理对象
             [self.delegate downLoadOperation:self didFishedDownLoad:imgae];
        });
    }
}
@end


主控制器中的业务逻辑:
复制代码
//
//  YYViewController.m
//  01-自定义Operation
//
//  Created by apple on 14-6-26.
//  Copyright (c) 2014年 itcase. All rights reserved.