我一直试图让这个工作一天,我仍然失败。我想在安装应用程序时从包中将大量文件复制到我的应用程序的Documents文件夹中,但这会让用户等待很长时间,应用程序会显示启动画面。
所以我想我会用UIProgressView创建一个初始的UIAlertView作为子视图,每次将文件复制到文档文件夹时都会更新。但是,警报显示并且进度条永远不会更新。我的逻辑是:
在- (void)didPresentAlertView:(UIAlertView *)alertView
执行for循环,复制文件并更新UI。代码是:
- (void)didPresentAlertView:(UIAlertView *)alertView{
NSString *src, *path;
src = // path to the Bundle folder where the docs are stored //
NSArray *docs = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:src error:nil];
float total = (float)[docs count];
float index = 1;
for (NSString *filename in docs){
path = [src stringByAppendingPathComponent:filename];
if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
... // Copy files into documents folder
[self performSelectorOnMainThread:@selector(changeUI:) withObject:[NSNumber numberWithFloat:index/total] waitUntilDone:YES];
index++;
}
}
[alertView dismissWithClickedButtonIndex:-1 animated:YES];
}
ChangeUI的代码是
- (void) changeUI: (NSNumber*)value{
NSLog(@"change ui %f", value.floatValue);
[progressBar setProgress:value.floatValue];
}
然而,这只是将UI从0更新为1,尽管NSLog会打印所有中间值。这里有没有人知道我做错了什么?
提前致谢。
答案 0 :(得分:2)
问题是你的循环在主线程上,因此UI直到最后都没有机会更新。尝试使用GCD在后台线程上完成工作:
dispatch_async(DISPATCH_QUEUE_PRIORITY_DEFAULT, ^
{
NSString *src, *path;
src = // path to the Bundle folder where the docs are stored //
NSArray *docs = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:src error:nil];
float total = (float)[docs count];
float index = 1;
for (NSString *filename in docs){
path = [src stringByAppendingPathComponent:filename];
if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
... // Copy files into documents folder
dispatch_async(dispatch_get_main_queue(), ^{ [self changeUI:[NSNumber numberWithFloat:index/total]]; } );
index++;
}
}
dispatch_async(dispatch_get_main_queue(), ^{ [alertView dismissWithClickedButtonIndex:-1 animated:YES]; } );
} );