Search code examples
swiftcocoansstoryboard

Casting failure with a view controller instantiated from a storyboard


I have a view controller that instantiates a new window controller. I need to pass an object to that window controller's view controller. Here is what I have so far:

let storyboard = NSStoryboard(name: "Main", bundle: nil)
if let windowController = storyboard.instantiateController(withIdentifier: "customerEditWindowController") as? NSWindowController
{
  let viewController = windowController.contentViewController as! EditCustomerViewController
  viewController.customer = customer // (An object)
  windowController.window?.makeKeyAndOrderFront(self)
}

The window is displayed as expected and then Xcode traps into the debugger with the error:

Could not cast value of type 'NSViewController' (0x7fffd1dcc4e0) to 'Inventory2.EditCustomerViewController' (0x100011660).

I'm confused since my EditCustomerViewController extends NSViewController.

class EditCustomerViewController: NSViewController

1) Why can't NSViewController be cast to EditCustomerViewController?
2) Is there a better way to get data into the new view controller?


Solution

  • This is a simple shot in the dark but did you set the view controller’s class name in Interface Builder?