码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-08-08 19:46:05      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

#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

 

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!