ios多线程操作(十)—— 用NSOperation开启多线程操作
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:(id) selector:(SEL) object:(id)]
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage:) object:@"Invocation"]; [op start];
- (void)downloadImage:(id)obj { NSLog(@"%@ - %@", [NSThread currentThread], obj); }
// 将操作添加到队列 -> 异步执行 @selector 方法 NSOperationQueue *q = [[NSOperationQueue alloc] init]; [q addOperation:op];
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{ }]
NSOperationQueue *q = [[NSOperationQueue alloc] init]; for (int i = 0; i < 10; ++i) { NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage:) object:@(i)]; // 将操作添加到队列 [q addOperation:op]; }
NSOperationQueue *q = [[NSOperationQueue alloc] init]; q.maxConcurrentOperationCount = 2; for (int i = 0; i < 10; ++i) { NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"睡1秒"); [NSThread sleepForTimeInterval:1.0]; NSLog(@"%@ - %d", [NSThread currentThread], i); }]; [q addOperation:op]; }
q.maxConcurrentOperationCount = 2;
[self.queue addOperationWithBlock:^{ NSLog(@"耗时的操作 %@", [NSThread currentThread]); // 在主线程更新 UI [[NSOperationQueue mainQueue] addOperationWithBlock:^{ NSLog(@"更新 UI %@", [NSThread currentThread]); }]; }];
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。