简体   繁体   English

无主参考导致泄漏,弱无效

[英]Unowned Reference causes leak , weak doesn't

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 . 我有一个UIViewController的子类,我手动设置它的视图,以便有一个返回viewController的引用,并避免引用循环我使用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. 现在的问题是,如果我使用unowned我有内存泄漏,但如果我使用weak我没有。 I can't figure out why this happens? 我无法弄清楚为什么会这样?

update: It seems like it's a bug. 更新:好像这是一个bug。

console output: 控制台输出:

removing vc
view Controller deinitialized
custom view deinitialized

I'm using xcode 8.3.1 我正在使用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 Release notes: Xcode 8.2发行说明:

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. 用于macOS和iOS模拟器的Memory Debugger修复了包含enum类型字段或从某些Objective-C框架类继承的类的Swift类的虚假内存泄漏报告。 (27932061) (27932061)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM