1

In my app when a user saves, lets say, a "favorite restaurant of the week" object, I first want to fetch all the restaurants I currently have saved in Core Data and check which ones are older than one week. I already have each of my Restaurant objects owning a dateSaved attribute that gets set when the object is saved.

After I delete all of the Restaurant objects that are older than a week, THEN I'll save the restaurant that the user selected to Core Data.

How do I get this done?

Rafi
  • 1,902
  • 3
  • 24
  • 46

1 Answers1

2

Fetch the records like so

NSManagedObjectContext *moc = …;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Restaurant"];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
if (!results) {
    DLog(@"Error fetching Restaurant objects: %@\n%@", [error localizedDescription], [error userInfo]);
    abort();
}

Then take the results array and enumerate like so:

NSMutableArray *newerRestaurantsArray = [NSMutableArray alloc] init];
for (id object in results){
//or use a block if you want
NSManagedObject *restaurant = (NSManagedObject *)object;

if (object.dateSaved > date a week ago){

[newRestaurantsArray addObject: object];
}

}

The newRestaurantsArray will have the ones you want. You then have to delete the ones you don't want or delete all of them and just save back the ones you want. Look at this tutorial that shows how to save and make it work for your implementation.

You can also use NSPredicate to get only the results you want. Check out this SO answer. To see how for your particular case.

Community
  • 1
  • 1
noobsmcgoobs
  • 2,716
  • 5
  • 32
  • 52
  • Thanks! I was more worried about whether I should delete them one by one and saved the context or delete a batch of them. Should I do this in a background thread? I'm a beginner to Core Data so I don't know how long it takes to delete multiple objects. – Rafi Apr 08 '16 at 22:56
  • 1
    You can do it in a background thread of course. It's a lot more complicated than doing it serially though. If you can find some good code that's reliable I'd go ahead and do it asych but there are huge caveats to doing so. – noobsmcgoobs Apr 09 '16 at 01:18
  • 1
    Now that I think about it, you should probably take a look at the `NSPredicate` answer. It's the most efficient way of doing it. I was just giving you an answer off the top of my head since it looked like you needed help fast. I don't use `Core Data` that often so that's why I didn't give a full answer re: `NSPredicate` and threading since I'm not up on it as much. – noobsmcgoobs Apr 09 '16 at 01:26
  • Thanks! So I'll first set an `NSDate` object to a date from a week ago like so: `NSDate *weekAgo = [today dateByAddingTimeInterval: -604800.0];`. And then I'll use a predicate like `[NSPredicate predicateWithFormat:@"dateSaved <= %@", weekAgo]]`. I think I got it now. – Rafi Apr 09 '16 at 05:54