iOS开发—自定义NSOperation子类下载图片

如果NSOperation的两个子类,NSInvocationOperation类和NSBlockOperation类无法满足需求,可以自定义一个继承自NSOperation的类。接下来通过一个下载图片的案例,展示如何使用自定义的NSOperation子类,这里暂时先介绍非并发的NSOperation,具体内容如下:

(1)新建一个SingleViewApplication工程,命名为“11-CustomNSOperation”;

(2)进入Main.StoryBoard ,从对象库中拖拽1个ImageView到程序界面,设置ImageView的Mode模式为Center,设置一个背景颜色,并且用拖拽的方式对这个控件进行属性声明;

(3)新建一个类DownloadOperation,继承于NSOperation类,表示下载操作。在DownloadOperation.m文件中,重写main方法,并且为该自定义类创建一个代理,并为该代理提供一个下载图片的方法,DownloadOperation类的声明和实现文件如下所示:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class DownloadOperation;
//定义代理
@protocol DownloadOperationDelegate<NSObject>
//下载操作方法
-(void)downloadOperation:(DownloadOperation *)operation
image:(UIImage *)image;
@end
@interface DownloadOperation:NSOperation
//需要传入图片的URL
@property(nonatomic,strong) NSString *url;
//声明代理属性
@property(nonatomic,weak) id<DownloadOperationDelegate> delegate;
@end


#import"DownloadOperation.h"
@implementation DownloadOperation
-(void)main
{
    @autoreleasepool{
    //获取下载图片的URL
        NSURL *url=[NSURL URLWithString:self.url];
    //从网络下载图片
        NSData *data=[NSData dataWithContentsOfURL:url];
    //生成图像
        UIImage *image=[UIImage imageWithData:data];
    //在主操作队列通知调用方更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"图片下载完成……");
        if([self.delegate respondsToSelector:
            @selector(downloadOperation:image:)]){
            [self.delegate downloadOperation:self image:image];
        }
        }];
    }
}
@end
DownloadOperation .m文件中,main方法实现了下载操作的功能,并通过downloadOperation:image:方法将下载好的图片通过代理的方式传递给代理方。

在ViewController.m文件中,创建NSOperationQueue队列,设置ViewController成为DownloadOperation的代理对象,创建自定义操作,并将自定义操作对象添加到NSOperationQueue队列中,最后刷新界面,代码如下:

#import "ViewController.h"
#import "DownloadOperation.h"
@interface ViewController ()<DownloadOperationDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //创建队列
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    //队列添加操作
    DownloadOperation *operation=[[DownloadOperation alloc] init];
    operation.delegate=self;
    operation.url=@"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1284235532,3794754795&fm=27&gp=0.jpg";
    //将下载操作添加到操作队列中去
    [queue addOperation:operation];
}
-(void)downloadOperation:(DownloadOperation *)operation image:(UIImage *)image
{
    self.imageView.image=image;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
运行程序,结果如下图所示:


从图中可以看出,自定义的NSOperation的子类同样实现了图片的下载操作。


猜你喜欢

转载自blog.csdn.net/shichunxue/article/details/78507303