swiftcore-datansmanagedobjectnsentitydescription

Issue understanding Core Data fundamentals


I'm creating an array of NSManagedObject to be used as my UITableView DataSource as follow :

let entity = NSEntityDescription.entityForName("YoutubeAsset", inManagedObjectContext: self.managedContext)!
let asset = YoutubeAsset(entity: entity, insertIntoManagedObjectContext: self.managedContext)
asset.videoId = code
myDataSource.append(asset)

And than, when the users selecting one of the cells, i want to save the specific object into my Core Data Entity.

The problem is that when i'm calling

 do {
        try managedContext.save()
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }

It's saves all of my DataSource into Core Data.

How can i "pull" only the selected object out of my managedContext, and save it into Core Data? Much appreciated, Roi!


Solution

  • If the managedContext has no unsaved objects at the beginning of your code sample, then saving the context at the end will result in a single SQL insert.

    You cannot save individual entities, just contexts (which save all entities in the context that are unsaved).

    If you want to make some changes and have them be unsaved, then you should make those changes in a different context.