概述
在iOS中除了可以使用NSThread來實現在自線程中執行任務,還可以使用封裝好的NSOperation。
涉及的主要的類:
- NSOperationQueue
- NSInvocationOperation
- NSInvocation
示例
例子中只是簡單的創建任務,並添加到任務隊列中。任務中完成一些簡單的操作(循環操作)。
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
//任務隊列實例化
NSOperationQueue* _queue;
}
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
for (int i=0; i<2; i++) {
UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100+80*i, 200, 40);
if (i==0) {
[btn setTitle:@"添加任務01到隊列中" forState:UIControlStateNormal];
}else if (i==1){
[btn setTitle:@"添加任務02到隊列中" forState:UIControlStateNormal];
}
[btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
btn.tag = 101 +i;
[self.view addSubview:btn];
}
//示例化一個任務隊列
_queue = [NSOperationQueue new];
//設置最大併發任務數量
[_queue setMaxConcurrentOperationCount:5];
}
-(void)pressBtn:(UIButton*)btn{
NSInteger tag = btn.tag;
if (tag == 101) {
//第一種方法
//創建一個執行任務
//p1:任務函數的持有者
//p2:任務函數
//p3:參數
//NSInvocationOperation* iop = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(opAct01:) object:nil];
//第二種方法,只是將相應的參數拆分開了
NSInvocation* invo = [NSInvocation new];
invo.target = self;
invo.selector = @selector(opAct01:);
NSInvocationOperation* iop = [[NSInvocationOperation alloc] initWithInvocation:invo];
//加入任務隊列中執行
[_queue addOperation:iop];
}else if (tag == 102){
//另一種
[_queue addOperationWithBlock:^{
while (true) {
NSLog(@"Block opt");
}
}];
}
}
-(void)opAct01:(NSInvocationOperation*) iop{
while (true) {
NSLog(@"invocation opt");
}
}
@end