Objective-C-NSoperationカスタム実装
2120 ワード
カスタムNSOperation mainメソッドを実装するには、内部コードにautoReleaseを追加します.
DownloadImg.h
DownloadImg.m
ViewController
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