iOS多线程技术
2016-03-02 11:04
435 查看
1. NSObject多线程
[selfperformSelectorInBackground:@selector(intoBackground)
withObject:nil];
[self
performSelectorOnMainThread:@selector(intoForword)
withObject:nil
waitUntilDone:YES];
2. NSThread多线程
创建子线程1.[NSThread detachNewThreadSelector:@selector(intoBackThread:) toTarget:self withObject:imageView];
2. NSThread *thread =[[NSThread
alloc]
initWithTarget:self
selector:@selector(intoBackThread:)
object:imageView];
[thread
start];
在子线程中进行的操作需要autoreleasepool
@autoreleasepool{}
回到主线程
[imageView performSelectorOnMainThread:@selector(setImage:)withObject:image waitUntilDone:YES];
3. NSOperation多线程
1.
// 利用队列设置同时并发的线程个数[self.queue
setMaxConcurrentOperationCount:4];
for (UIImageView *imageView
in self.dataArray) {
NSInvocationOperation *operation = [[NSInvocationOperation
alloc] initWithTarget:self
selector:@selector(operationCilck:)
object:imageView];
//
队列(一定要记住)
[self.queue
addOperation:operation];
}
2.
@autoreleasepool {[self.queue
setMaxConcurrentOperationCount:4];
for (UIImageView *imageView
in self.dataArray) {
NSBlockOperation *blockOperation = [NSBlockOperation
blockOperationWithBlock:^{
[NSThread
sleepForTimeInterval:1.0f];
//
在线程中作多线程加载资源
UIImage *image = [UIImage
imageNamed:[NSString
stringWithFormat:@"NatGeo%02ld.png",(long)arc4random_uniform(17)
+ 1]];
//
得到UI线程
[[NSOperationQueue
mainQueue] addOperationWithBlock:^{
[imageView
setImage:image];
}];
}];
[self.queue
addOperation:blockOperation];
}
}
}
在子线程中进行的操作需要autoreleasepool
回到主线程
[imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];4. GCD多线程
// 队列初始化(全局队列)dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0);
// 同步:一步一步做
异步:同时做
for (UIImageView *imageView
in self.dataArray) {
//
进入多线程
dispatch_async(queue, ^{
NSLog(@"%@",[NSThread
currentThread]);
UIImage *image = [UIImage
imageNamed:[NSString
stringWithFormat:@"NatGeo%02ld.png",(long)arc4random_uniform(17)
+ 1]];
dispatch_async(dispatch_get_main_queue(), ^{
[imageView
setImage:image];
});
});
}
}
相关文章推荐
- ios 文本转语音 播报 AVSpeechSynthesizer
- Nagios中常见参数的含义
- iOS获取设备型号、设备类型等信息
- iOS多线程之NSOperation的使用
- IOS模拟器上下部分黑屏(界面未占满)解决办法
- didReceiveMemoryWarning-内存警告处理方法-iOS
- iOS9 上支付宝AlipaySDK编译错误解决办法
- 【理解】 iOS沙盒(sandbox)机制(二)
- iOS 控制台unicode转中文
- iOS应用程序生命周期
- iOS获取设备型号、设备类型等信息
- 【理解】 iOS沙盒(sandbox)机制(一)
- Nagios+NRPE安装备忘录(二)
- iOS Error = NSURLErrorDomain Code=-1022 " 错误解决
- iOS拨打电话(三种方法)
- iOS多线程之GCD的基本使用
- ios开发--编码格式
- 【解决方法】【技术】22个iOS开发的小技巧
- iOS开发手势---拖动、捏合、旋转、点按、长按、轻扫
- iOS开发在类的头文件中要尽可能少的引入其他头文件