*由于GCD的线程开出去之后就没法管理,所以苹果又推出NSOperaton
NSOperation和NSOperationQueue实现多线程
1.先将需要执行的操作封装到一个NSOperation对象中
2.然后将NSOperation对象添加到NSOperationQueue中
3.系统会自动将NSOperation中封装的操作放到一条新线程中执行
1.传值方法
- (void)testInvocation {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//NSOperationQueue *queue = [NSOperationQueue mainQueue];
NSInvocationOperation *invocation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task:) object:@"abc"];// [invocation start];
[queue addOperation:invocation];}
打印
- (void)task:(NSString *)str {
NSLog(@"%@--%@",str,[NSThread currentThread]);}
2.1block块方法
- (void)testBlockOperate {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"block task1 %@",[NSThread currentThread]);
}];
[block addExecutionBlock:^{
NSLog(@"block task2 %@",[NSThread currentThread]);
}];
//[block start];
[queue addOperation:block];}
2.2
- (void)addQueueBlock {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
NSLog(@"task1 %@",[NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
NSLog(@"task2 %@",[NSThread currentThread]);
}];}
调用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// [self testInvocation];
// [self testBlockOperate];
[self addQueueBlock];}
网友评论