Twitter 和 Fabric 中的内存泄漏 - Swift

Memory leak in Twitter and Fabric - Swift

我的模态登录 window 在我关闭它时解除分配 OK,直到我通过 Fabric 添加 Twitter Kit 登录按钮。

import TwitterKit

// UIview that I have in my login view controller
@IBOutlet weak var twitterLoginView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Twitter integration
    let twitterLogInButton = TWTRLogInButton { (session, error) in
        if let unwrappedSession = session {
            let alert = UIAlertController(title: "Logged In",
                message: "User \(unwrappedSession.userName) has logged in",
                preferredStyle: UIAlertControllerStyle.Alert
            )
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        } else {
            NSLog("Login error: %@", error!.localizedDescription);
        }
    }
    // add to twitter UIView
    twitterLoginView.addSubview(twitterLogInButton)

}

我认为存在一个保留周期,但由于或多或少他们建议的代码,我不知道如何解决这个问题。即使我不按 Twitter 按钮,只是关闭登录 window,登录 window 也不会解除分配,因此添加按钮的行为导致了问题。删除推特按钮,它就会解除分配。有什么想法吗?

可能是因为闭包中的自实例捕获。尝试使用弱自我:

override func viewDidLoad() {
    super.viewDidLoad()

    // Twitter integration
    let twitterLogInButton = TWTRLogInButton { [weak self] (session, error) in
        guard let s = self else {return}
        if let unwrappedSession = session {
            let alert = UIAlertController(title: "Logged In",
                message: "User \(unwrappedSession.userName) has logged in",
                preferredStyle: .Alert
            )
            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            s.presentViewController(alert, animated: true, completion: nil)
        } else {
            NSLog("Login error: %@", error!.localizedDescription);
        }
    }
    // add to twitter UIView
    twitterLoginView.addSubview(twitterLogInButton)
}