【问题标题】:Unowned Reference causes leak , weak doesn'tUnowned Reference 会导致泄漏,weak 不会
【发布时间】:2017-04-14 12:10:09
【问题描述】:

我遇到了某种内存管理问题。我有一个UIViewController 的子类,我手动设置它的视图,以便引用回viewController 并避免使用weak/unowned 的引用循环。 现在的问题是,如果我使用unowned,我有内存泄漏,但如果我使用weak,我没有。我不知道为什么会这样?

更新: 好像是个bug。

控制台输出:

removing vc
view Controller deinitialized
custom view deinitialized

我使用的是 xcode 8.3.1

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = ViewController(nibName: nil, bundle: nil)
    window?.makeKeyAndVisible()

    DispatchQueue.main.asyncAfter(deadline: .now() + 5) { 
        print("removing vc")
        self.window?.rootViewController = nil
    }

    return true
}


class ViewController: UIViewController {

    override func loadView() {
        view = CustomView(frame: .zero, vc: self)
        view.backgroundColor = .red
    }

    deinit {
        print("view Controller deinitialized")
    }
}

class CustomView:UIView{

    init(frame: CGRect , vc:ViewController) {
        self.vc = vc
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //    weak var vc : ViewController!   // no leak
    unowned var vc : ViewController   // leak

    deinit {
        print("custom view deinitialized")
    }
}

【问题讨论】:

  • 你如何确定你有泄漏?也许您的方法是错误的,或者这(不太可能)是编译器错误
  • 仪器和内存图都表明,这是一个泄漏。
  • weak 和 unowned 都没有强引用。所以它不能成为泄漏的原因。见:stackoverflow.com/a/26025176/6595536
  • 请@Alan 尝试覆盖deinit 并在那里打印一些信息并以这种方式检查,因为用于 swift 的工具工具可能还不能正常工作。我个人在那里遇到了误报。也许你的泄漏甚至不是泄漏。
  • 你使用 Xcode 8.1.3 吗?泄漏工具存在官方问题。尝试使用 Xcode 8.2 再次检查!

标签: ios swift memory-leaks automatic-ref-counting


【解决方案1】:

Xcode 8.2 发行说明:

macOS 和 iOS 模拟器的内存调试器修复了 包含任一类型字段的 Swift 类的错误内存泄漏 枚举,或从某些 Objective-C 框架继承的类 类。 (27932061)

【讨论】:

    猜你喜欢
    • 2013-01-10
    • 2022-06-13
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2021-09-25
    • 2014-12-08
    相关资源
    最近更新 更多