Aeradriel
Aeradriel

Reputation: 1232

Instance variable reset to nil at ViewDidLoad()

I have an object that inherits from UIViewController. In this object, I have a instance variable that contain the profile of the user (type: UserProfile). I'm setting this variable before ViewDidLoad() but once I enter in it, the variable is reseted to nil...

Here is my code:

    class MapViewController: UIViewController {

        var userProfile: UserProfile!

        required init(coder: NSCoder) {
            super.init(coder: coder)
        }

        override init() {
            super.init()
        }

        override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
            super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        }

        func setProfile(userProfile: UserProfile) {        
            self.userProfile = userProfile
            //self.userProfile is OK
        }

        override func viewDidLoad() {
            super.viewDidLoad()
            self.userProfile is equal to nil....
       }
}

Here is the declaration of the controller:

self.mapViewController = MapViewController()
self.mapViewController?.setProfile(self.userProfile)
//The controller is pushed through the storyboard

Upvotes: 3

Views: 1317

Answers (1)

Matz
Matz

Reputation: 1006

you create a new instance of MapViewController here:

self.mapViewController = MapViewController()
self.mapViewController?.setProfile(self.userProfile)
//The controller is pushed through the storyboard

You should use your destinationcontroller from segue:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) 
{
    if (segue.identifier == "showSecondViewController")
    {
        var second = segue.destinationViewController as SecondViewController
        second.setProfile(...)
    }
}

Upvotes: 2

Related Questions