ios - didReceiveMemoryWarning,viewDidUnload

标签 ios objective-c

我在读一本书,它建议将我的 IBOutlets 声明为 weak 应该可以解决当我的应用程序收到内存不足警告时的问题。例如,我现在不再需要在 viewDidUnload 方法中将这些 socket 设置为 nil。

我还听说在 iOS6 中 viewDidUnload 被弃用,取而代之的是 didReceiveMemoryWarning 被调用。

无论如何,我该如何继续,我是否应该将我的 IBOutlet 声明为 weak,并“忘记”实现 didReceiveMemoryWarningsviewDidUnloads?

最佳答案

不是所有的 IBOutlets 都应该是 weak。来自Apple docs (Resource Programming guide)的推荐

Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create should therefore typically be weak, because:

  • Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.

  • The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).

例子:

XIB 中的顶级对象应声明为strong,任何其他 subview /控件应为weak 属性。

    @property (nonatomic, weak)   IBOutlet MyView *viewContainerSubview;
    @property (nonatomic, strong) IBOutlet MyOtherClass *topLevelObj;

使用 ARC weak 生命周期限定符有其自身的优势(Refer Apple docs)因为,

__weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.

因此您不必担心设置 IBOutlets nil,它的生命周期自动受其顶级实例的约束。

应实现

didReceiveMemoryWarning 以清除任何占用内存的可重新创建资源。当您收到 didReceiveMemoryWarning 调用时,它应该用于释放使用的非关键资源,例如:自定义数据结构、用于填充 UI 的网络服务响应等。任何资源需求的非关键性由开发者决定。

关于ios - didReceiveMemoryWarning,viewDidUnload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18378866/

相关文章:

ios - 如何从现有的 Xcode 项目中删除 Apple Watch 应用程序?

ios - CocoaPods 找不到 pod "firebase_auth": In Podfile 的兼容版本

objective-c - 子类化 UIButton 以处理点击

objective-c - SpriteKit 缺少线性变换矩阵

ios - 在iPhone的个人热点网络上查找设备

ios - 在 iOS 应用程序中实现 OsmAnd

ios - UIProgressView 一直重置为 0.0

ios - 缺少营销图标 Xcode bug?

ios - 将值从 iOS native 代码传递到 cordova

ios - 如何在应用程序 bundle 中编辑文件?