Reputation: 1922
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?
Upvotes: 1
Views: 905
Reputation: 2746
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.
Upvotes: 2