开发者

Setting a property value on each of the results in a FetchedResults set

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:)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜