Espen Birk
Espen Birk

Reputation: 456

Passing data to "unknown" viewcontroller

I have lots of viewcontrollers, spread over many storyboards.

Is there any way to pass data to a viewcontroller, when only knowing the viewcontroller identifier.

The viewcontroller identifier and storyboard name is is read from a plist, and the viewcontroller is loaded like this:

let storyboard = UIStoryboard(name: plistdata.storyboard, bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: menuItem.identifier)
navigationController?.pushViewController(vc, animated: true)

Since i cant cast the viewcontroller as the proper class, i cant set the data. Can a class be casted from a string, something like

let vc = storyboard.instantiateViewController(withIdentifier: menuItem.identifier) as! ClassFromString("MyDestinationViewController")

Or would it be a better approach to have the datamodel keep track of which viewcontroller is being pushed, and fetch the necessary data in the destination viewcontroller as soon as it loads?

Upvotes: 0

Views: 58

Answers (2)

Zee
Zee

Reputation: 327

I think Best approach is Segue... Because Segue make Array of your ViewControllers so it is easy to push, pop, and send data.

Upvotes: 0

matt
matt

Reputation: 535315

When you don't know the class of something, but you want to be able to talk to it anyway, that's what a protocol is for. If every one of your anonymous view controller classes adopts MyProtocol, and if MyProtocol requires a takeData method, then you can cast vc to a MyProtocol and call takeData with no further information about what class this view controller is.

Upvotes: 1

Related Questions