0

Let's say I load in 1,000 objects via Core Data, and each of them has a user-settable Favorite boolean. It defaults to NO for all objects, but the user can paw through at will, setting it to YES for as many as they like. I want a button in my Settings page to reset that Favorite status to NO for every single object.

What's the best way to do that? Can I iterate through every instance of that Entity somehow, to set it back? (Incidentally, is 'instance' the right word to refer to objects of a certain entity?) Is there a better approach here? I don't want to reload the data from its initial source, since other things in there may have changed: it's not a total reset, just a 'Mass Unfavourite' option.

Luke
  • 9,512
  • 15
  • 82
  • 146
  • Is the emoticon and 'thanks in advance' that was in here before the edit an issue, Josh? I like letting people know I'm not expectant, and am grateful for all the help I've received here. Anything to make Core Data a little less formal and dreary! – Luke Feb 25 '13 at 18:58
  • It's considered unnecessary/noise, yes, although it's not the end of the world, and it's a stretch to edit just because of that: [Should 'hi', 'thanks', taglines, and salutations be removed from posts?](http://meta.stackexchange.com/q/2950) My main focus was making the title a little more specific and clear, addressing your desired result, rather than your possible solution. – jscs Feb 25 '13 at 20:02

1 Answers1

0

Okay, I've gotten it to work, but it requires a restart of the app for some reason. I'm doing this:

- (IBAction) resetFavourites: (id) sender
{
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    [fetch setEntity: [NSEntityDescription entityForName: @"Quote" inManagedObjectContext: [[FQCoreDataController sharedCoreDataController] managedObjectContext]]];
    NSArray *results = [[[FQCoreDataController sharedCoreDataController] managedObjectContext] executeFetchRequest: fetch error: nil];
    for (Quote *quote in results) {
        [quote setIsFavourite: [NSNumber numberWithBool: NO]];
    }

    NSError *error;
    if (![self.fetchedResultsController performFetch: &error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    [self.tableView reloadData];
}

This works fine if I close and re-open the app, but it isn't reflected immediately. Isn't that what the reloadData should do, cause an immediate refresh? Am I missing something there?

Luke
  • 9,512
  • 15
  • 82
  • 146
  • You didn't save changes, for one thing, but normally (at least in Apple's Core Data template code) your changes get saved when the app is going to exit. Also, you can speed this up a little by using an `NSPredicate` to only fetch instances where `isFavorite` is `NO` instead of every instance. – Tom Harrington Feb 25 '13 at 19:22