magicalpanda / MagicalRecord

Super Awesome Easy Fetching for Core Data!
Other
10.8k stars 1.79k forks source link

Update records in swift 3 #1298

Closed ShahVivek closed 5 years ago

ShahVivek commented 7 years ago

I want to add/update/delete records using MagicalRecord in swift 3. I am able to add and fetch records. But I don't know how can I update multiple records. I am fetching records using below method

mr_findAll(with searchTerm: NSPredicate?)

Can anyone help me that , how can I update this records?

ryancarlson commented 7 years ago

I can think of a couple different ways:

MagicalRecord.save(blockAndWait: { (context) 
  let predicate = NSPredicate( ... )
  let models = MyModel.mr_find(with: predicate, in: context)

  for model in models {
    model.foo = "bar"
  }
}

or:

let context = NSManagedObjectContext.mr_default()
let predicate = NSPredicate( ... )
let models = MyModel.mr_findAll(with: predicate, in: context)

for model in models {
  model.foo = "bar"
}
context.mr_saveToPersistentStoreAndWait()

Of course you don't have to use the methods that block until saving if you don't want to. Hope this helps!

vishaldeshai commented 6 years ago

Plz use same code as you used for add record but use attributes with primary key for e.g take a key like 'ID' as a primary. when you save(update) then record will be updated.

Coeur commented 5 years ago

Documentation has been recently updated to include Swift code.

Also, thank you @ryancarlson for your great examples.