views:

24

answers:

1

Hi

On my Core Data Entity "Book" i have a boolean property, 'wasViewed' (NSNumber numberWithBool) that tells me if the Book was "viewed".

I would like to implement a sort of "reset" this property for all my NSManagedObjects "Book". So that I can set them all to NO between sessions. I use an NSPredicate to retrieve all the Books like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"wasViewed == %@", [NSNumber numberWithBool:YES]];

// code for setting entity, request etc...

NSMutableArray *mutableFetchResults = [[[managedObjectContext executeFetchRequest:request error:&error] mutableCopy] autorelease];

This is working just fine, however, now I need to set up a loop, go through each Book object, something like this:

for(Book *b in mutableFetchResults) {

    [b setWasViewed:NO]
}

Is there a way to perform an action on each element that fits the predicate instead of retrieving it? So instead of executeFetchRequest on a managedObjectContext it could be executeOperationOnFetchRequestResults or something along those lines.

Thanks for any input given:)

+1  A: 

Core Data does not provide that kind of a convenience function. In order to update sets of objects, you will need to do it 'manually'. If you're concerned about the number of lines of code, you could condense your example down to:

[mutableFetchResults makeObjectsPerformSelector:@sel(setWasViewed:) withObject:[NSNumber numberWithBool:NO]];

You could also change your 'wasViewed' attribute to something like 'lastViewed' which is a NSDate. Instead of marking the book as viewed, you simply update 'lastViewed' to the current time. You can then determine if a book was viewed in the current session by checking if the books 'lastViewed' time is greater than the session start time.

CJ
Hi CJThank you, I was mostly concerned about having to fetch results I didn't need for anything else than setting a single property to true. I hoped there was something like makeObjectsPerformSelector for a fetch.But I guess it would be diverging from the way you usually use core data. Get and object, change it, persist it.I do like your "one-liner" it is as easy to read as a loop and more compact.
RickiG
PS. I do have a "lastViewed" Date, this one is just for a few special cases, which also was why I didn't like to "reserve" bot a fetch and a loop for it:). Good advice still!
RickiG