标签:
#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
标签:
原文地址:http://www.cnblogs.com/tangranyang/p/4713721.html