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

  • 相关阅读:
    [转]编译原理书籍推荐
    [转]让 Dreamweaver 支持 Emmet(原ZenCoding)
    [转]Zend Studio GitHub 使用教程
    [转]如何用EGit插件把github上的项目clone到eclipse
    [转]github更新自己fork的代码
    [转]少走弯路:学习编译原理的相关建议
    [转]关于计算机研究生报考方向的简要介绍
    [转]zend studio 安装git插件
    [转]如何在SAE上安装原版wordpress
    C语言博客作业02循环结构
  • 原文地址:https://www.cnblogs.com/tangranyang/p/4713702.html
Copyright © 2011-2022 走看看