zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    闰年的定义
    Sublime Text 3
    维特比算法(Viterbi)
    索引
    倒排索引
    URL过滤
    判断一个元素是否在集合中
    布隆过滤器
    jsp九大内置对象
    jsp九大内置对象和其作用详解
  • 原文地址:https://www.cnblogs.com/tangranyang/p/4713702.html
Copyright © 2011-2022 走看看