iOS NSOperation 封装 通知实现界面更新

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@interface MYOperation : NSOperation


@end

 

#import "MYOperation.h"


@implementation MYOperation


-(void)main

{

    //不管是ARC还是MRC一定要用autorelease来释放c语言对象

    @autoreleasepool {

        //NSString *image=[self stringEith];

        //发布通知

        //[[NSNotificationCenter defaultCenter] postNotificationName:@"MYOperation" object:image];

        [self stringEith];

        

        [self downLoadImage:@"URL"];

    }

    

    

}

//模拟下载 跳到主进程模拟发送通知,通知控制器更新UI

-(NSString*)stringEith

{

    NSString*image= @"大坏蛋!!!!";

    [[NSOperationQueue mainQueue]addOperationWithBlock:^{

        [[NSNotificationCenter defaultCenter] postNotificationName:@"MYOperation" object:image];

    }];

    return image;

}




//下载

-(UIImage *)downLoadImage:(NSString*)str

{

    NSURL *url=[NSURL URLWithString:str];

    NSData *data=[NSData dataWithContentsOfURL:url];

    UIImage*image=[UIImage imageWithData:data];

    

    [[NSOperationQueue mainQueue]addOperationWithBlock:^{

        [[NSNotificationCenter defaultCenter] postNotificationName:@"MYOperation" object:image];

    }];

    //return image;

    

    return image;

    

}

@end

 

 

//控制器代码

 

#import "ViewController.h"

 

#import "MYOperation.h"


@interface ViewController ()


@property(nonatomic,strong)NSOperationQueue*queue;


@property(nonatomic,strong)NSString*str;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    //发送通知的是在子进程,这里接收通知执行方法也是在子进程中执行,,发送通知是在主进程,这里接收通知执行方法也是在主进程中执行,一般情况下更新UI是在主进程中进行,所以这里我们应该默认让接收事件方法在主进程中执行\

    需要在拓展类中进行操作

    //注册通知事件

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateImage:) name:@"MYOperation" object:nil];

    

    

    

}


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

{

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

    //监听

    [self.queue addOperation:operation];

    

    

    

}

//

-(void)updateImage:(NSNotification*)notification

{

    self.str=notification.object;

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

}



//注册的通知事件一定要移除

-(void)dealloc

{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

}



-(NSOperationQueue*)queue

{

    if (!_queue) {

        _queue=[[NSOperationQueue alloc]init];

        //设置最大线程数

        [_queue setMaxConcurrentOperationCount:6];

    }

    return _queue;

}


@end

 

转载于:https://www.cnblogs.com/tangranyang/p/4713721.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值