• 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

  • 相关阅读:
    只能输入正整数 以及常用的正则表达式 (转载)
    SVN cleanup操作反复失败解决办法 (转载)
    关于${pageContext.request.contextPath}的理解 (转载)
    Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds
    一则Oracle EXP导出报错的解决办法(转载)
    js数组的sort排序详解(转载)
    JavaScript arguments对象(转载)
    转 :meta name的含义
    一些小问题
    005.JMS可靠性机制
  • 原文地址:https://www.cnblogs.com/tangranyang/p/4713702.html
Copyright © 2020-2023  润新知