objective-c - 在后台线程上加载 Nib

标签 objective-c ios nib grand-central-dispatch loadnibnamed

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

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

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

我不需要详细说明代码在做什么,但我的问题是:

如果在后台线程中调用 loadNibNamed 并且加载的 View 被 nib 加载过程缓存,那么主线程也想要加载该 nib - 但从缓存中加载它。当我的对象被释放时 - 从背景中的 Nib 加载的 View 是否也在背景中释放..??真的没有意义,因为无论如何后台线程将不再存在....

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

最佳答案

来自 Mike Ash 的文章

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.

关于objective-c - 在后台线程上加载 Nib ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9264850/

相关文章:

ios - 如何以编程方式分配 UIView 自动布局边缘以匹配 super View ?

ios - 如何在 Objective c 中使用 SAP WSDL 服务?

带有 ARC 的结构中的 Objective-C 类

ios - ALAssetLibrary 通知和 enumerateAssetsUsingBlock

ios - 在spritekit中旋转一个子节点

iOS:如何从 UIMenuController 获取选定的 UIMenuItem

view - 使用 xib 创建自定义 View

iphone - 对 nib 文件感到困惑

xcode - 将第二个 Interface Builder XIB 文件基于现有文件

ios - 我必须等待 Alamofire 完成发布请求还是全部异步