在后台线程上加载笔尖

发布于 2025-01-04 22:41:44 字数 497 浏览 5 评论 0原文

我刚刚花了一天时间追踪一个非常奇怪的错误。这是一个 UILabel 被过度释放,尽管在代码中没有过度释放。如果我注释掉标签的发布,代码就可以了。

我追踪到一个在后台线程中发布的 UIView。这似乎不对,因为您应该从主线程访问所有 UI 元素。然后,我发现一个正在后台线程中加载的 nib 文件,使用:

[[NSBundle mainBundle] loadNibNamed:@"nib name" owner:self options:nil];

我不需要详细了解代码正在执行的操作,但我的问题是:

如果在后台线程中调用 loadNibNamed 并加载视图由 nib 加载过程缓存,然后主线程也想加载该 nib - 但从缓存加载它。当我的对象被释放时 - 从后台笔尖加载的视图是否也在后台释放..?确实没有意义,因为无论如何后台线程都将不再存在......

我不知道,但我通过将 GCD 分派中的代码的 loadNibNamed 部分同步包装到主线程来解决它。

I just spent a day tracking down a really weird bug. It was a UILabel being overreleased, although in the code there was no over-releasing. If I commented out the release of the label, code was fine.

I tracked it down to a UIView that was being released in a background thread. Which didn't seem right as you're supposed to access all UI elements from the main thread. I then found a nib file that was being loaded in a background thread using:

[[NSBundle mainBundle] loadNibNamed:@"nib name" owner:self options:nil];

I don't need to go into the details of what the code was doing, but my question is:

If loadNibNamed is called in a background thread and the view loaded is cached by the nib loading process, then the main thread wants to load that nib too - but loads it from a cache. When my object is released - is the view loaded from the nib in the background also released in the background..?? Doesn't really make sense as the background thread would no longer exist anyway....

I don't know, but I resolved it by wrapping the loadNibNamed part of the code in a GCD dispatch onto main thread synchronously.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

〗斷ホ乔殘χμё〖 2025-01-11 22:41:44

来自 Mike Ash 的文章

危险的可可调用

NSBundle
这有NSHost一半的问题。 NSBundle 返回共享对象,但不是线程安全的,因此它只是主线程。从主线程使用它仍然是安全的。我将其标记为危险的原因是因为从辅助线程使用它是不安全的事实并没有真正记录下来,而是必须从它不是线程安全的事实以及实例是共享的事实来推断,并且它可以很容易从其他线程中使用它。

From Mike Ash's article

Dangerous Cocoa Calls

NSBundle
This one has half of the problems of NSHost. NSBundle returns shared objects, but is not thread safe, so it's main-thread only. It's still safe to use from the main thread. The reason I mark it as dangerous is because the fact that it's unsafe to use from secondary threads is not really documented, but rather has to be inferred from the fact that it's not thread safe and the fact that the instances are shared, and it can be tempting to use it from other threads.

梦在夏天 2025-01-11 22:41:44

所有与 UI 相关的操作都应该在主线程中完成。

All UI-related operations should be done from the main thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文