code_junkie

Programmatically Update an attribute in Core Data

Nov 13th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. id | title
  2. ============
  3. 1 | Foo
  4. 2 | Bar
  5. 3 | FooFoo
  6.  
  7. NSError *saveError;
  8. [bookTwo setTitle:@"BarBar"];
  9. if (![managedObjectContext save:&saveError]) {
  10. NSLog(@"Saving changes to book book two failed: %@", saveError);
  11. } else {
  12. // The changes to bookTwo have been persisted.
  13. }
  14.  
  15. NSError *error = nil;
  16.  
  17. //This is your NSManagedObject subclass
  18. Books * aBook = nil;
  19.  
  20. //Set up to get the thing you want to update
  21. NSFetchRequest * request = [[NSFetchRequest alloc] init];
  22. [request setEntity:[NSEntityDescription entityForName:@"MyLibrary" inManagedObjectContext:context]];
  23. [request setPredicate:[NSPredicate predicateWithFormat:@"Title=%@",@"Bar"]];
  24.  
  25. //Ask for it
  26. aBook = [[context executeFetchRequest:request error:&error] lastObject];
  27. [request release];
  28.  
  29. if (error) {
  30. //Handle any errors
  31. }
  32.  
  33. if (!aBook) {
  34. //Nothing there to update
  35. }
  36.  
  37. //Update the object
  38. aBook.Title = @"BarBar";
  39.  
  40. //Save it
  41. error = nil;
  42. if (![context save:&error]) {
  43. //Handle any error with the saving of the context
  44. }
  45.  
  46. bookTwo.title = @"BarBar";
  47.  
  48. [bookTwo setValue:@"BarBar" forKey:@"title"];
Add Comment
Please, Sign In to add comment