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

后端 未结 14 2694
有刺的猬
有刺的猬 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:39

    Updated for Swift 4 & XCode 9.2

    To answer your question...

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

    You first need to get a reference to your AppDelegate and viewContext. You then need to set up a NSFetchRequest for the Entity you are looking to update, in my example that would be "Alert". You then set up your fetch to find the result you are looking for. In the example, my result found Alerts by their creation date and alert type.

    To further read how to query using a predicate. Stack Overflow Example & Apple Documentation

    I then context.fetch(fetchRequest), set the results to the value I wanted to update, and dealt with errors in a try catch. Finally I context.save().

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest(entityName: "Alert")
    
    fetchRequest.predicate = NSPredicate(format: "creationDate = %@ AND alertType = %&",
                                             argumentArray: [creationDate, alertType])
    
    do {
        let results = try context.fetch(fetchRequest) as? [NSManagedObject]
        if results?.count != 0 { // Atleast one was returned
    
            // In my case, I only updated the first item in results
            results[0].setValue(yourValueToBeSet, forKey: "yourCoreDataAttribute")
        }
    } catch {
        print("Fetch Failed: \(error)")
    }
    
    do { 
        try context.save() 
       }
    catch {
        print("Saving Core Data Failed: \(error)")
    }
    

提交回复
热议问题