How do you update a CoreData entry that has already been saved in Swift?

后端 未结 14 2722
有刺的猬
有刺的猬 2020-11-30 00:55

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         


        
14条回答
  •  无人及你
    2020-11-30 01:31

    Swift >= 2 the method now returns a non-optional and throws an error in the error case, which must be handled with try-catch:

        let context = self.fetchedResultsController.managedObjectContext
        let entity = self.fetchedResultsController.fetchRequest.entity!
    
        let fetchRequest = NSFetchRequest(entityName:entity.name!)
        fetchRequest.predicate = NSPredicate(format: "notificationId = 13")
    
        do {
            let list = try context.executeFetchRequest(fetchRequest) as? [NSManagedObject]
            if list!.count == 0 // Check notificationId available then not save
            {
                let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
                newManagedObject.setValue("This is first message13", forKey: "message")
                newManagedObject.setValue(1, forKey: "appId")
                newManagedObject.setValue(13, forKey: "notificationId")
                newManagedObject.setValue("First one", forKey: "tital")
            }
            // success ...
        } catch let error as NSError {
            // failure
            print("Fetch failed: \(error.localizedDescription)")
        }
    

提交回复
热议问题