Search code examples
swiftcore-data

Update all value in one attribute Core Data


I know how to fetch all value from one attribute in Core Data using an array. I just need to press a button and -1 all the value and save it back to the Core Data.

How can I update all the value once in swift?

Thanks.


Solution

  • Try following example it might be helpful.Replace you entity name.

      var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    
      var context: NSManagedObjectContext = appDel.managedObjectContext!
      var request = NSFetchRequest(entityName: "Params")
      var params = NSEntityDescription.insertNewObjectForEntityForName("Params", inManagedObjectContext: context) as! NSManagedObject
    
      if let fetchResults = appDel.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
    
           if fetchResults.count != 0{
                 for (var v = 0 ; v < fetchResults.count ; v++) {
                  var managedObject = fetchResults[v]
    
                 println(fetchResults)
                 managedObject.setValue("-1", forKey: "value")
                 context.save(nil)
    
                    }
            }
      }