在我的应用程序中,我需要使用 Grand Central Dispatch (CGD) 在后台执行大量操作(调整一组图像的大小)。
我有EngineViewController
一个应用程序的 rootViewController 类:
AppDelegate.m
EngineViewController * engineVc = [[EngineViewController alloc]init];
self.window.rootViewController = engineVC;
在我的viewDidAppear
方法中,engineVC
我有以下代码:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//this method resize a set of image and save them in Document Folder of the app
//this method needs about 40 seconds to perform all operations
[[JSONParser sharedJSONParser]writeToDiskResizedImage];
NSLog(@"Finished");
});
}
方法[[JSONParser sharedJSONParser]writeToDiskResizedImage]
返回后,NSLog
在控制台中打印消息和应用程序崩溃。我所有的项目都是 ARC,JSONParser
上课除外。在控制台中没有错误消息;我只有这个:
执行的代码[[JSONParser sharedJSONParser]writeToDiskResizedImage]
如下:
CGFloat screenScale = [UIScreen mainScreen].scale;
NSString * imagePath = [[NSBundle mainBundle]pathForResource:imageName ofType:nil];
//UIImage * image = [UIImage imageWithContentsOfFile:imagePath];
UIImage * image = [[UIImage alloc]initWithContentsOfFile:imagePath];
CGSize newImageSize = [image resizeImageSettingWidth:(kArticleImageWidth * screenScale)];
UIGraphicsBeginImageContext(newImageSize);
[image drawInRect:CGRectMake(0,0,newImageSize.width,newImageSize.height)];
UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (image) {
[image release];
}
NSData *jpegData = UIImageJPEGRepresentation(newImage, 0.9f);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString * newImageName;
if ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] &&
([UIScreen mainScreen].scale == 2.0)) {
newImageName = [NSString stringWithFormat:@"%@-article@2x.jpg", [imageName stringByDeletingPathExtension]];
}
else {
newImageName = [NSString stringWithFormat:@"%@-article.jpg", [imageName stringByDeletingPathExtension]];
}
NSLog(@"newImageName %@", newImageName);
NSString *filePath = [documentsPath stringByAppendingPathComponent:newImageName]; //Add the file name
[jpegData writeToFile:filePath atomically:YES]; //Write the file
if (newImage) {
[newImage release];
}
if (jpegData) {
[jpegData release];
}