gpt4 book ai didi

iOS - 何时在主线程中调用 UI 更改函数

转载 作者:行者123 更新时间:2023-11-29 12:14:34 25 4
gpt4 key购买 nike

每次我对我的服务器进行 API 调用以获取数据时,我已经知道我必须使用以下 block 来执行 UI 更改命令,因为我的 API 调用是在后台线程中执行的:

dispatch_async(dispatch_get_main_queue(), ^{
//do UI stuff
});

但是,如果我有一个函数可以在 API 调用 block 之外更改 UI 内容怎么办?例如:

-(void)doALotOfUIChanging
{
//do a lot of UI changing
}

在我的 API 调用 block 中,我是否需要像这样在主线程中调用该 UI 更改函数?:

[apiObject getDataFromObject:my.Object successCallback:^(Array *data) 
{
dispatch_async(dispatch_get_main_queue(), ^{
[self doALotOfUIChanging];
});
}
errorCallback:^(NSString *error)
{
NSLog(@"%@", error);
}];

或者我是否不必在主线程中调用它,因为该函数已经像这样在 API 调用 block 之外?:

[apiObject getDataFromObject:my.Object successCallback:^(Array *data) 
{
[self doALotOfUIChanging];
}
errorCallback:^(NSString *error)
{
NSLog(@"%@", error);
}];

我也有对其他 View Controller 执行转场的函数,所以我也想知道我是否也应该在主线程中调用它们。我正在做一些代码清理,我不想在我可能不需要的情况下不断重写 dispatch_async 函数,所以任何帮助或建议将不胜感激。谢谢。

最佳答案

简短回答:是的,您应该在主线程上更新您的 UI。

Threads and Your User Interface

If your application has a graphical user interface, it is recommended that you receive user-related events and initiate interface updates from your application’s main thread. This approach helps avoid synchronization issues associated with handling user events and drawing window content. Some frameworks, such as Cocoa, generally require this behavior, but even for those that do not, keeping this behavior on the main thread has the advantage of simplifying the logic for managing your user interface.

There are a few notable exceptions where it is advantageous to perform graphical operations from other threads. For example, you can use secondary threads to create and process images and perform other image-related calculations. Using secondary threads for these operations can greatly increase performance. If you are not sure about a particular graphical operation though, plan on doing it from your main thread.

引用:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html

关于iOS - 何时在主线程中调用 UI 更改函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322661/

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