这是我的代码:
-(IBAction)saveDownloadedImage
{
NSLog(@"Test"); EXECUTED
indicatorView.hidden = NO; NOT EXECUTED
[indicatorView startAnimating]; NOT EXECUTED
[statusLabel setText:@"WHY?"]; NOT EXECUTED
[currentPicture setImage:[imageView image]]; EXECUTED
ImageFileManager *fileManager = [[ImageFileManager alloc] init]; EXECUTED
[fileManager saveImageToDisk:currentPicture]; EXECUTED
indicatorView.hidden = YES;
[statusLabel setText:@"Image saved successfully."]; EXECUTED
saveButton.enabled = NO; EXECUTED
}保存过程大约需要5秒钟。因此,在用户界面中看到指示器是正常的。但是什么也没发生!任何想法?
最佳答案
一切都执行了。您的问题是saveImageToDisk
调用是同步的,并且您正在从UI线程调用它。当您阻止UI线程时,不会重绘任何内容。显示了指示器,但是直到IBAction
返回时(如果将其再次隐藏),它才可以绘制到屏幕上。
您必须异步调用保存方法。
阻止UI线程绝不是一个好主意。
编辑:请参阅以下问题的答案以获取正确的解决方案:asynchronous calls to database in ios
Edit2:可能的解决方案之一(未经测试)
-(IBAction)saveDownloadedImage {
indicatorView.hidden = NO; //Note you can use hidesWhenStopped property for this
[indicatorView startAnimating];
[statusLabel setText:@"BECAUSE..."];
[currentPicture setImage:[imageView image]];
[NSThread detachNewThreadSelector:@selector(save) toTarget:self withObject:nil]
}
- (void)save {
@autoreleasepool {
ImageFileManager *fileManager = [[ImageFileManager alloc] init];
[fileManager saveImageToDisk:currentPicture];
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
}
}
- (void)updateUI {
indicatorView.hidden = YES;
[statusLabel setText:@"Image saved successfully."];
saveButton.enabled = NO;
}