3
我遇到某種內存管理問題。我有一個UIViewController
的子類,我手動設置其視圖以便參考回viewController
並避免參考週期I使用weak/unowned
。 現在的問題是,如果我使用unowned
我有內存泄漏,但如果我使用weak
我沒有。我無法弄清楚爲什麼會發生這種情況?無主參考導致泄漏,薄弱不
更新: 這似乎是一個錯誤。
控制檯輸出:
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")
}
}
您如何確定您有泄漏?也許你的方法是錯誤的,或者這是(不太可能)編譯器錯誤 – Alistra
儀器和內存圖顯示,這是一個泄漏。 – Alan
既不弱也不無主持。所以它不能成爲泄漏的原因。請參閱:http://stackoverflow.com/a/26025176/6595536 – ObjectAlchemist