我可以从互联网下载 ZIP 文件。后处理在connectionDidFinishLoading 中完成,并且工作正常,但没有更新UIView 元素。例如,我设置 statusUpdate.text = @"Uncompressing file" 但该更改直到 connectionDidFinishLoading 完成后才会出现。同样,UIProgressView 和 UIActivityIndicatorView 对象在该方法结束之前不会更新。
有什么方法可以强制在此方法中更新 UIView 吗?我尝试设置 [self.view setNeedsDisplay] 但这不起作用。它似乎在主线程中运行。这里的所有其他命令都可以正常工作 - 唯一的问题是更新 UI。
Thanks!
更新:这是不更新 UIVIEW 的代码:
-(void)viewWillAppear:(BOOL)animated {
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(processUpdate:) userInfo:nil repeats:YES];
downloadComplete = NO;
statusText.text = @"";
}
-(void)processUpdate:(NSTimer *)theTimer {
if (! downloadComplete) {
return;
}
[timer invalidate];
statusText.text = @"Processing update file.";
progress.progress = 0.0;
totalFiles = [newFiles count];
for (id fileName in newFiles) {
count++;
progress.progress = (float)count / (float)totalFiles;
// ... process code goes here ...
}
}
在 processUpdate 结束时,我设置 downloadComplete = YES。此构建和运行不会出现错误,并且按预期工作,除了在 processUpdate 完成之前 UIVIEW 中没有任何更新,然后所有内容都会立即更新。
感谢您一直以来的帮助!
正如 Niels 所说,如果您想看到视图更新,则必须将控制权返回给运行循环。但除非确实需要,否则不要开始分离新线程。我推荐这种方法:
- (void)connectionDidFinishLoading:(NSConnection *)connection {
statusUpdate.text = @"Uncompressing file";
[self performSelector:@selector(doUncompress) withObject:nil afterDelay:0];
}
- (void)doUncompress {
// Do work in 100 ms chunks
BOOL isFinished = NO;
NSDate *breakTime = [NSDate dateWithTimeIntervalSinceNow:100];
while (!isFinished && [breakTime timeIntervalSinceNow] > 0) {
// do some work
}
if (! isFinished) {
statusUpdate.text = // here you could update with % complete
// better yet, update a progress bar
[self performSelector:@selector(doUncompress) withObject:nil afterDelay:0];
} else {
statusUpdate.text = @"Done!";
// clean up
}
}
基本思想是你要分小块进行工作。您从方法返回以允许运行循环定期执行。对performSelector: 的调用将确保控制权最终返回到您的对象。
请注意,这样做的风险是用户可能会按您可能意想不到的方式按下按钮或与 UI 交互。调用 UIApplication 可能会有所帮助beginIgnoringInteractionEvents
在工作时忽略输入...除非您想表现得非常好并提供一个取消按钮来设置您签入的标志doUncompress
方法...
您也可以尝试自己运行运行循环,调用[[NSRunLoop currentRunLoop] runUntilDate:...]
经常这样,但我从未在自己的代码中尝试过。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)