I\'m not sure what I\'m doing wrong here, but when I save the first time into coredata, it works just fine. When I try to overwrite that, it doesn\'t.
func t
var context:NSManagedObjectContext = appDel.managedObjectContext!
var en = NSEntityDescription.entityForName("ENTITIES_NAME", inManagedObjectContext: context)
let batchUpdateRequest = NSBatchUpdateRequest(entity: en!)
batchUpdateRequest.resultType = NSBatchUpdateRequestResultType.UpdatedObjectIDsResultType
batchUpdateRequest.propertiesToUpdate = ["OBJECT_KEY": "NEWVALUE"]
var batchUpdateRequestError: NSError?
context.executeRequest(batchUpdateRequest, error:&batchUpdateRequestError)
if let error = batchUpdateRequestError {println("error")}
good luck
Swift 5
You can create a method that can work to both, include and update.
Considering you have an entity created on CoreData with the name Users
:
var context: NSManagedObjectContext
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
let user: Users!
let fetchUser: NSFetchRequest<Users> = Users.fetchRequest()
fetchUser.predicate = NSPredicate(format: "id = %@", id as String)
let results = try? context.fetch(fetchUser)
if results?.count == 0 {
// here you are inserting
user = Users(context: context)
} else {
// here you are updating
user = results?.first
}
user.id = id
user.name = name
...
try context.save()