iOS NSOperation 异步加载图片 封装NSOperation 代理更新

#import <Foundation/Foundation.h>

@class MYOperation;

@protocol MYOperationDelecate <NSObject>


-(void)operationWithStr:(UIImage*)str;


@end


@interface MYOperation : NSOperation

 @property(nonatomic,copy)NSString *imageURL;

@property(nonatomic,weak)id<MYOperationDelecate>delegate;

@end

#import "MYOperation.h"




@implementation MYOperation


//必须实现main方法

-(void)main

{

    @autoreleasepool {

        //模拟下载图片返回的字符串在主进程中返回到控制器进行跟新操作

        UIImage*str=[self downloadImage];

        [[NSOperationQueue mainQueue]addOperationWithBlock:^{

            if([self.delegate respondsToSelector:@selector(operationWithStr:)])

            {

                [self.delegate operationWithStr:str];

            }

        }];

        

        

        

        

    };

}




//模拟下载图片


-(UIImage*)downloadImage

{

    

   NSURL *url=[NSURL URLWithString:self.imageURL];

    NSData *data=[NSData dataWithContentsOfURL:url];

    UIImage*image=[UIImage imageWithData:data];    

    return image;

}


@end

//控制器加载代码

#import "ViewController.h"

#import "MYOperation.h"


@interface ViewController ()<MYOperationDelecate>


@property(nonatomic,strong)NSOperationQueue*operation;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    MYOperation *operation=[[MYOperation alloc]init];

    operation.delegate=self;

     operation. imageURL=@"www.baidu.com/image";

    [self.operation addOperation:operation];

}


-(void)operationWithStr:(UIImage*)str

{

#warning 在这里实现UI界面的更新

    NSLog(@"%@,%@",str,[NSThread currentThread]);

}


-(NSOperationQueue *)operation

{

    if(!_operation)

    {

        _operation=[[NSOperationQueue alloc]init];

        [_operation setMaxConcurrentOperationCount:6];

    }

    return _operation;

}


@end

原文地址:https://www.cnblogs.com/tangranyang/p/4713702.html