您的位置:首页 > 移动开发 > Objective-C

Objective-C-NSOperation自定义实现

2016-03-03 00:00 561 查看
摘要: NSOperation自定义子类

自定义 NSOperation要实现main方法,内部代码加上 autoRelease

DownloadImg.h

@class UIImage;
@class DownLoadOperation;

@protocol DownLoadOperationDelegate <NSObject>
@required
- (void) downloadOperation:(DownLoadOperation*) opertaion finishDownloadImg:(UIImage *)img;
@end

@interface DownLoadOperation : NSOperation
/** 要传递到operation中的属性*/
@property (nonatomic, strong) NSString *urlStr;
/** 用来通知下载图片生成KO*/
@property (nonatomic, weak) id<DownLoadOperationDelegate> delegate;
@end

DownloadImg.m

#import <UIKit/UIKit.h>

@implementation DownLoadOperation

- (void) main
{
@autoreleasepool {
if (self.isCancelled) {
return;
}
NSURL *url = [NSURL URLWithString:self.urlStr];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];

if (self.isCancelled) {
return;
}
//update UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if ([self.delegate respondsToSelector:@selector(downloadOperation:finishDownloadImg:)]) {
[_delegate downloadOperation:self finishDownloadImg:img];
}
}];
}
}
@end

ViewController

#import "DownLoadOperation.h"

@interface ViewController ()<DownLoadOperationDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imgView;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if (_imgView.image) {
return;
}
DownLoadOperation *operation = [[DownLoadOperation alloc] init];
operation.urlStr = @"http://img4.duitang.com/uploads/item/201406/01/20140601231235_WRKGW.jpeg";
operation.delegate = self;

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
}

- (void)downloadOperation:(DownLoadOperation *)opertaion finishDownloadImg:(UIImage *)img
{
_imgView.image = img;
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 iOS NSOperation