【发布时间】:2012-08-13 03:07:44
【问题描述】:
当我的应用程序第一次启动时,我需要将一些(大约 300-400 张图像)复制到文档文件夹中。我看到的是它需要很长时间的工具(即使现在我认为我只用 30-40 张图像进行测试)。一开始我的应用程序在手机上(不是在模拟器上)运行时崩溃,因为运行时间太长。现在我正在运行复制线程上所有文件的方法。该应用程序保持运行,但我认为 ios 会在几秒钟后杀死该线程。我应该将每个图像副本放在一个新线程上吗???
我的代码是这样的:(这是线程中运行的部分)
-(void) moveInitialImagesFromBundleToDocuments {
//move all images.
NSMutableArray *images = [MyParser getAllImagesList];
for (int i = 0 ; i< [images count] ; i++) {
[self copyFileFromBundleToDocuments:[images objectAtIndex:i]];
}
}
- (void) copyFileFromBundleToDocuments: (NSString *) fileName {
NSString *documentsDirectory = [applicationContext getDocumentsDirectory];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSLog(@"Source Path: %@\n Documents Path: %@ \n Destination Path: %@", sourcePath, documentsDirectory, destinationPath);
NSError *error = nil;
[self removeFileFromPath:destinationPath];
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
NSLog(@"File %@ copied", fileName);
NSLog(@"Error description-%@ \n", [error localizedDescription]);
NSLog(@"Error reason-%@", [error localizedFailureReason]);
}
有什么建议吗?首先是为了让复制更快,其次,我应该为我复制的每个文件创建一个新线程吗?
评论1:
这看起来不错。但我想调暗应用程序,以便用户在加载所有图像之前无法使用该应用程序。
我在 .它确实阻止了用户运行应用程序,但我认为在手机上,线程正在被杀死,因为当我尝试它时,加载时间太长。实际上从未停止过。
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = @"preparing...";
hud.dimBackground = YES;
hud.square = YES;
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// Do something...
FileUtil *fileut = [[FileUtil alloc] init];
[fileut moveInitialImagesFromBundleToDocuments];
//Done something
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
});
【问题讨论】:
-
为什么需要复制图像?您可以在它们所在的位置很好地访问它们。如果您在 /Documents 中有混合图像,您总是可以定义一些方法来处理“罐装”图像和其他修改过的图像。您通过复制文件在用户设备上浪费了 200M 的空间。另一个想法是将文档文件夹链接或“符号链接”到捆绑包 - 有点复杂(我相信必须使用 C api)但会更快(如果它有效),因为您将创建一个文件系统指针而不是复制文件。
-
我同意 David H. 副本的意义何在?据我所知,从捆绑包中提取图像是一种完全合法的做法。
-
问题是用户必须能够从互联网获取数据更新。所以我不能覆盖捆绑包中的文件。所以我需要将它们放在 doc 文件夹中。
标签: iphone multithreading image copy