Search code examples
swiftnsviewcontroller

Setting a value in one file from another programmatically [Swift]


Not the same as: Passing values ... and Swift - programmatically ... was not helpful for my situation.

When I press a button in one file (NSViewController)

@IBAction func bookPressed(sender: NSButton) { 
    var popVC = NSStoryboard(name: "Main", 
        bundle: nil)?.instantiateControllerWithIdentifier("PopoverViewController") as? NSViewController
    popVC.bookName = "hello"
}

I want this file to show the results of bookName = "hello"

class PopoverViewController: NSViewController {

    let bookName: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        println(bookName)
    }
}

What am I missing?


Solution

  • You need to cast popVC as PopoverViewController so you can set the bookName property, as NSViewController does not have a property bookName:

    var popVC = NSStoryboard(name: "Main", 
        bundle: nil)?.instantiateControllerWithIdentifier("PopoverViewController") as? PopoverViewController
    

    Then you will need to present the view controller you just instantiated using presentViewController(_:animated:completion:)

    Furthermore, in your PopoverViewController class, you should use var for bookName because it is immutable as is.