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

How do I save a CKRecord as Core Data?

How do I save a CKRecord as Core Data?

1 Answer

It depends on how complicated your CKRecord is. For something simple (no relationships in CD), I'd pull from CK, convert from CKRecord to whatever the values are natively (String, Int, Bool, etc.), create a NSManagedObject class to store the converted values, then save to CoreData. CoreData can get quite confusing pretty quickly so I would recommend looking at a tutorial on RayWenderlich, for example (provided you've not used it before), but in the simplest form (assuming you've set up the AppDelegate with CoreData when you created the project. If not - this is a great resource:

//assume an instance of this has been set above somewhere. Something like: ClassYouvePreviouslyDefined.stringVariable = "This is the string you previously converted from the CKRecord and set to the stringVariable in the ClassYouvePreviouslyDefined Class"

//retrieve the app delegate to access CD
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

//Grab the entity that you have defined in your xcDataModel.
let entity = NSEntityDescription.entityForName("EntityNameYouCreatedInYourXCDataModel", inManagedObjectContext:managedContext)
let variableName = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
//set value of data to the key you created in the XCDataModel
variableName.setValue(ClassYouvePreviouslyDefined.stringVariable, forKey: "yourKeyNameYouCreatedInTheXCDataModel")
//
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)") 
}