Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nick Sint
4,208 PointsPassing custom NSObject between View Controller Swift
Hi,
My question is how do I pass a custom object between View Controllers.
Assume there is FirstViewController and SecondViewController. Also assume there is an NSObject called CustomObject
I'd imagine using segues to pass the data but the problem is the initialisation of the custom object. For example:
//In FirstViewController
.
.
.
let index = 0
let dataToPass = array[index] as CustomObject
self.performSegueWithIdentifier("segue", sender: dataToPass)
.
.
.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segue"{
let destinationVC:FirstViewController = segue.destinationViewController as FirstViewController
destinationVC.temp= sender
}
}
.
.
.
My problem in FirstViewController is that the line "destinationVC.temp= sender" gives me the following error:
"Cannot convert the expression's type '()' to type 'CustomObject' "
//In SecondViewController
.
.
.
class SecondViewController:UIViewController{
let temp:CustomObject
.
.
.
}
In SecondViewController, I get the error: "Class SecondViewController has no initialisers". TO fix this error, xcode keeps prompting me to implement
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
But I don't actually know what this does
Any help would be much appreciated!
1 Answer
Jason Wayne
11,688 PointsThe problem in the FirstViewController in the segue method is as what the error is saying. The sender is type AnyObject, which cannot be converted to type NSObject, CutomObject.
In your SecondViewController, you are not instantiating the constant. You are just declaring the type of the constant which is CutomObject, which is type NSObject. Try, changing it to let temp = CustomObject() or var temp = CustomObject().
In your FirstViewController, you should consider creating a variable or constant called temp as well. That way, throughout the entire code, just use self.temp.
Once that is done, in your segue method in the FirstViewController, assign destination.temp = self.temp.
That should work. Hope it points you to the right direction. =]