您的位置:首页 > 产品设计 > UI/UE

UI 实现多线程方式之三 NSOperation+NSOperationQueue

2015-10-05 21:01 423 查看
#pragma mark 方式三 NSOperation

//第一种 NSInvocationOperation,单独使用必须手动开启线程。

NSInvocationOperation *invocation = [[NSInvocationOperation
alloc]initWithTarget:self
selector:@selector(subThread3)
object:nil];

[invocation
start];

//第二种 NSBlockOperation,单独使用必须用手动开启线程。

__weak
typeof(self) temp =
self;

NSBlockOperation *block = [NSBlockOperation
blockOperationWithBlock:^{

[temp
subThread4];

}];

[block
start];

====================================

//第三种 和NSOperationQueue结合使用

NSInvocationOperation *invocation1 = [[NSInvocationOperation
alloc]initWithTarget:self
selector:@selector(subThread3)
object:nil];

//一定要记得 block内部会持有
对象,需要在外面 用 __weak
修饰。

__weak
typeof(self) temp =
self;

NSBlockOperation *block1 = [NSBlockOperation
blockOperationWithBlock:^{

[temp
subThread4];

}];

//可以通过NSOperationQueue创建队列,向队列中添加操作。完成多任务同时执行。

NSOperationQueue *queue = [[NSOperationQueue
alloc]init];

#warning 注意:一定要提前设置好并发数--最大并发数(同时最多只有两个线程分享处理器)

[queue setMaxConcurrentOperationCount:2];

//添加进队列中
[queue
addOperation:invocation1];
[queue
addOperation:block1];

==========================================

#pragma mark 子线程

-(void)subThread3
{

@autoreleasepool {

NSLog(@"子线程3");
}
}

-(void)subThread4
{

@autoreleasepool {

NSLog(@"子线程4");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: