ios - NSURLSession 应该是一个弱属性吗

标签 ios nsurlsession

我正在调查内存泄漏,通过使用 Malloc 选项,它看起来像我们拥有的一个类:

enter image description here

SessionManager 类有

@property(nonatomic, strong) NSURLSession *urlSession;

- (instancetype)initWithConfiguration(NSURLSessionConfiguration)configuration {
    if (self = [super init]) {
    _urlSession = [NSURLSession sessionWithConfiguration:configuration delgate: self delegateQueue:_sessionQueue];


    }

    return self;
}

我不确定如何阅读它,除非我能猜到,它是 NSURLSession 持有 SessionManager 以及 SessionManager 对 NSURLSession 的强引用。 NSURLSession 的属性应该是 weak 还是 unowned?

其次,如果是这样,原因是什么?

最佳答案

你的假设是正确的。来自 documentation :

Discussion

This delegate object is responsible for handling authentication challenges, for making caching decisions, and for handling other session-related events. The session object keeps a strong reference to this delegate until your app exits or explicitly invalidates the session. If you do not invalidate the session, your app leaks memory until it exits.

这基本上就是您所写的内容。你有双面强引用循环。正如您所说,您可以通过将 urlSession 设置为 weak 引用来破坏它。然而,这可能(但不是必需的)导致不良的副作用,例如在创建 urlSession 后立即丢失,因为没有对象捕获对它的强引用。

我的建议

  • 确保这部分代码确实能产生一些重大影响 内存泄漏(因为现在它看起来像一种简单的单例,不应该占用太多内存)
  • 如果它真的会导致内存泄漏 - 重新考虑您的架构,这样您就可以 invalidate sessions .

附言

如果您的主要目标是调查内存泄漏,那么在调试内存图以分析对象计数器和 Xcode 的提示(紫色矩形中的感叹号)时查看 Xcode 的左侧面板会很有帮助。

关于ios - NSURLSession 应该是一个弱属性吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47984066/

相关文章:

ios - 在后台使用 NSURLSession 一个一个地下载 100 个文件的列表

ios - 调试 URLSession(在 iOS 10 中)

ios - Swift - 处理 subview

ios - 如何消除NavigationBar?

iphone - 用于 iOS 或 objective-c 端口的 libphonenumber

ios - downloadTaskWithRequest 混淆行为(swift,IOS)

ios - NSURLSession 准确设置请求超时

使用 URLSession 下载完成后 iOS 快速通知

iOS 如何制作一个函数来接受确认到 NSCoding 的参数

ios - UICollectionView - 选择随机单元格