无主引用会导致泄漏,弱不会 [英] Unowned Reference causes leak , weak doesn't

查看:100
本文介绍了无主引用会导致泄漏,弱不会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到某种内存管理问题.我有一个UIViewController的子类,并且我手动设置了它的视图,以便获得对viewController的引用,并避免使用weak/unowned的引用周期. 现在的问题是,如果我使用unowned,则会发生内存泄漏,但是如果我使用weak,则不会发生内存泄漏.我不知道为什么会这样?

I'm experiencing some kind of memory management issue. I have a subclass of UIViewController and I set its view manually in order to have a reference back to the viewController and to avoid reference cycle I use weak/unowned. Now the problem is , if I use unowned I have a memory leak but if I use weak I don't have one. I can't figure out why this happens?

更新: 看来是个错误.

update: It seems like it's a bug.

控制台输出:

removing vc
view Controller deinitialized
custom view deinitialized

我正在使用xcode 8.3.1

I'm using 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")
    }
}

推荐答案

Xcode 8.2发行说明:

Xcode 8.2 Release notes:

适用于macOS和iOS Simulator的Memory Debugger修复了有关以下内容的报告: 包含两个类型的字段的Swift类的错误内存泄漏 枚举或继承自某些Objective-C框架的类 类. (27932061)

The Memory Debugger for macOS and the iOS Simulator fixes reporting of false memory leaks for Swift classes containing either fields of type enum, or classes that inherit from certain Objective-C framework classes. (27932061)

这篇关于无主引用会导致泄漏,弱不会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆