gpt4 book ai didi

ios - 为什么我的 UI 会在我明确离开返回主线程时更新

转载 作者:行者123 更新时间:2023-11-29 00:17:42 25 4
gpt4 key购买 nike

根据这个问题,UI更新必须在主线程上完成https://stackoverflow.com/a/23155684/1898829

[[session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
if (data != nil) {
NSDictionary *responseDictionary =
[NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
// dispatch_async(dispatch_get_main_queue(), ^{
CarListModel *carListModel = [[CarListModel alloc]
initWithArray:responseDictionary[@"placemarks"]];
completion(carListModel, error);
// });
} else {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}
}] resume];

注释掉dispatch_async(dispatch_get_main_queue(), ^{ 我的应用程序仍然像以前一样工作。我的表格 View 得到更新,我的事件指示器停止。

此完成 block 转到 View 模型,该 View 模型具有一个转到 View Controller 的完成 block 。我没有说它必须返回主线程。

为什么我的 UI 没有被阻止,或者它是否可以返回到主线程而无需我使用

显式设置它
dispatch_async(dispatch_get_main_queue(), ^{

最佳答案

您说得对,UI 更新必须在主线程上完成。您错误地认为不在主线程上执行此操作将导致没有任何操作发生。如果真是这样就好了。如果您不在主线程上进行 UI 更新,应用程序可能会随时以奇怪和意外的方式失败。这意味着它可能会在几分钟后崩溃。动画可能会突然停止工作。 View 可以随机消失或出现。导航栏可能不合适。换句话说,行为是未定义的。

因此你应该

1) 从后台线程更新 UI 时始终使用 dispatch_async(dispatch_get_main_queue(), ^{

2) 如果你有一个可能被后台线程意外调用的方法,用类似的东西保护它们:

if (![NSThread mainThread]) {
// log to crash reporter without crashing
NSError* error = [NSError errorWithDomain:@"accessing UI outside of main thread" code:-1 userInfo:nil];
[[Crashlytics sharedInstance] recordError:error withAdditionalUserInfo:@{@"file":__FILE__, @"line":@(__LINE__)}];
return;
}

关于ios - 为什么我的 UI 会在我明确离开返回主线程时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44868863/

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