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

iOS Build a Selfie App with Swift 2 Saving and Displaying Selfies Displaying Photos

Could not cast value of type 'NSManagedObject_Photo_' (0x608000058360) to 'FaceSnap.Photo' (0x106227db0).

Received this error message after clicking on "Save" button.

I followed the code provided by Pasan except for changes due to Swift 3.

Code as follows:

class func photo(withImage image: UIImage) -> Photo {
    let photo = NSEntityDescription.insertNewObject(forEntityName: Photo.entityName, into: CoreDataController.sharedInstance.managedObjectContext) as! Photo

    photo.date = NSDate().timeIntervalSince1970

    photo.image = UIImageJPEGRepresentation(image, 1.0)! as NSData

    return photo
}

2 Answers

This should solve your problem:

go to the model data, select the Photo Entity, show utilities (the right sidebar), than navigate to model data inspector and make sure that you Class Module is set to Current Product Model

This is my working code

class func photo(withImage image: UIImage) -> Photo {
        let photo = NSEntityDescription.insertNewObject(forEntityName: entityName, into: CoreDataController.sharedInstance.managedObjectContext) as! Photo

        photo.date = Date().timeIntervalSince1970
        photo.image = UIImageJPEGRepresentation(image, 1.0)!

        return photo
    }