skymook skymook - 3 months ago 43
iOS Question

Memory leak in Twitter and Fabric - Swift

My modal login window deallocates OK when I close it, until I add Twitter Kit login button via Fabric.

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)

}


I think there is a retain cycle, but with more or less the code they suggested, I'm at a loss on how to fix this. Even if I don't push the twitter button, and just close the login window, the login window does not deallocate, so the act of adding the button is causing the problem. Remove the twitter button, and it deallocates. Any ideas?

Answer

Probably because of self-instance capture in closure. Try to use weak self:

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)
}
Comments