標籤:
#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
iOS NSOperation 封裝 通知實現介面更新