我有以下代码:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Loading Content For the First Time..."
message:@"\n"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = CGPointMake(139.5, 75.5); // .5 so it doesn't blur
[alertView addSubview:spinner];
[spinner startAnimating];
[alertView show];
for (TCMLevelRemote *level in [obj objectForKey:@"levels"]){
[[TCMExhibitFeedStore sharedStore] createLevel:level];
}
[[TCMExhibitFeedStore sharedStore] loadAllLevels];
[[TCMExhibitFeedStore sharedStore] setAllLevels:[[TCMExhibitFeedStore sharedStore] storedLevels]];
[alertView dismissWithClickedButtonIndex:0 animated:YES];
for循环需要一段时间才能执行,因为它会在应用程序首次运行时下载一些信息。因此,我希望显示该通知,以便用户不会坐在无响应的屏幕上等待。问题是直到for循环结束后才显示alertview。然后它就马上消失了。我需要更改什么?
最佳答案
在 .h 类中声明您的alert-view
对象,以便在 .m 类中的任何地方使用。
将for循环代码放入performSelectorInBackground
中,以便在Backgroud中运行循环,这样您Alertview就不必等待ForLoop完成了。
[self performSelectorInBackground: @selector(LoadForLoop) withObject: nil];
-(void)LoadForLoop
{
for (TCMLevelRemote *level in [obj objectForKey:@"levels"]){
[[TCMExhibitFeedStore sharedStore] createLevel:level];
}
[[TCMExhibitFeedStore sharedStore] loadAllLevels];
[[TCMExhibitFeedStore sharedStore] setAllLevels:[[TCMExhibitFeedStore sharedStore] storedLevels]];
[alertView dismissWithClickedButtonIndex:0 animated:YES];
}
其他解决方案
您还可以按照您的代码像波纹管一样使用Grand Central Dispatch (GCD):-
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Loading Content For the First Time..."
message:@"\n"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = CGPointMake(139.5, 75.5); // .5 so it doesn't blur
[alertView addSubview:spinner];
[spinner startAnimating];
[alertView show];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (TCMLevelRemote *level in [obj objectForKey:@"levels"]){
[[TCMExhibitFeedStore sharedStore] createLevel:level];
}
[[TCMExhibitFeedStore sharedStore] loadAllLevels];
[[TCMExhibitFeedStore sharedStore] setAllLevels:[[TCMExhibitFeedStore sharedStore] storedLevels]];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner StopAnimating];
[alertView dismissWithClickedButtonIndex:0 animated:YES];
});
});
关于ios - ios:UIAlertView在for循环执行之前立即显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17306039/