NSOperationQueue 列队
常用示例:
NSOperationQueue *queue = [NSOperationQueue new];
[queue addOperationWithBlock:^{
}
//创建一个子线程列队,子线程为并行列队
NSOperationQueue *queue = [NSOperationQueue new];
[queue addOperationWithBlock:^{
NSLog(@"子线程");
//mainQueue为主线程列队,主线程为串行列队
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
NSLog(@"主线程");
}];
}];
我们如果写一个把网络图片缓存到本地的方法,就会用到多线程
示例:
@implementation UIImageView (ImageCached)
- (void)setImageViewWithURL:(NSURL *)url{
//缓存路径
NSString *basePath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
//如果路径是空的就返回
if(url.absoluteString.length == 0){
return;
}
//创建列队 定义文件名为url 的绝对路径
NSOperationQueue *queue = [NSOperationQueue new];
NSString *fileName = [self fileNameWithURL:url.absoluteString];
//定义缓存文件路径
NSString *cacheFilePath = [basePath stringByAppendingPathComponent:fileName];
//如果有这个缓存文件 if([[NSFileManager defaultManager]fileExistsAtPath:cacheFilePath isDirectory:nil]){
[queue addOperationWithBlock:^{
//读取cacheFilePath看看有没有我们要的图片文件
NSData *imageData = [NSData dataWithContentsOfFile:cacheFilePath];
//如果有imageData的话
if(imageData){
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
//就在主线程的image上显示
self.image = [UIImage imageWithData:imageData];
}];
}
}];
}else{
[queue addOperationWithBlock:^{
//从url下载图片
NSData *data = [NSData dataWithContentsOfURL:url];
//如果有data
if(data){
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
//显示到image上
self.image = [UIImage imageWithData:data];
//并且存到缓存路径中
[data writeToFile:cacheFilePath atomically:YES];
}];
}
}];
}
}
- (NSString*)fileNameWithURL:(NSString*)urlString{
//文件名 把url用/符号分割,取最后一个元素作为名字
NSArray *tempArray = [urlString componentsSeparatedByString:@"/"];
NSString *fileName = [tempArray lastObject];
return fileName;
}
@end