gpt4 book ai didi

objective-c - 如何在同步后正确处理 UI 刷新

转载 作者:行者123 更新时间:2023-11-29 13:28:27 24 4
gpt4 key购买 nike

我有一个应用程序,它在每次启动时使用 Rails 后端与服务器同步数据。 API 完全可用,但我遇到了一个问题,即当界面需要刷新时界面变得无响应。

我目前正在使用 GCD 开始同步:

Sync *sync = [[Sync alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[sync force_sync:@""];
[appModel updateSyncTime:current_time];
});

同步完成后,我让 Sync 对象向应用程序发送 NSNotification,以便界面刷新:

dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"Sync-Completed" object:self];
});

收到通知后,我的其他类只是简单地重新加载 UITableView 中的数据,如下所示:

 - (void)notificationReceived:(NSNotification *)notification {
[dataTable reloadData];
}

在收到通知之前,UI 是完全响应式的。收到通知后,在刷新完成之前,您无法在其他 UI 元素之间滚动 UITableView。我确信有更好的方法来做到这一点,但如何做呢?

提前致谢!

最佳答案

dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"Sync-Completed" object:self];
});

不是异步的——您只是在主队列中丢弃了大量的刷新工作(同步完成通知的处理)——所以您的应用将被锁定,除非您处理更新 UI 的代码。

此外,使用全局队列进行繁重的 IO 操作也不一定是个好主意。我已经看到这样做会锁定 UI 的情况 - 所以请确保它是通知而不是同步本身。

如果您发现它是同步本身 - 创建您自己的 NSOperation 队列并从该 block 创建一个 NSOperation。

你的里程可能会有所不同,但一般来说,使用全局队列对我来说对异步 IO 不起作用。

关于objective-c - 如何在同步后正确处理 UI 刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12461535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com