私のアプリでは、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];
}