Reputation: 776
I have a Parent <-->>
Child relationship (to-many).
And the relationship is when i need to fetch all child(s), Parent.children = (NSSet *) child(s)
There are times when I just need only one, latest entity based on a timeStamp attribute of the Child entity.
I was wandering what would be the easiest way to fetch it, easier than say creating a fetch request and setting fetch limit One and using a sort descriptor to order it based on timeStamp.
Is there an easier way? just calling maybe :
[Parent.children firstObject];
The reason is I'm gonna need to fetch it many times, through out the life of the app. In some cases, i though i'd have to fetch the latest Child entity in the -(void)awakeFromFetch() of a Parent Entity
.. and thats why i wanted to have a way thats more easier than anything else specially in terms of memory.
When Fetching Child entities, i kinda fetch a bunch of them that are child to 2 or more Parent entities using this predicate :
NSPredicate *pred = [NSPredicate predicateWithFormat:@"forParent IN %@", [Array of Parents]];
From the resultant NSSet, since i'd get all the required Child entities for the said object, it would be very convenient if I could allot a pointer to a latest child in according to its timeStamp attribute (NSDate).
Obviously after I'd get the NSSet result i could iterate over each child and allot a pointer to the latest entity i find in the NSSet, but it looks pretty painstaking, though i'd have to allot just one pointer to the latest entity of a particular Parent , iterating an NSSet which potentially could have more than a hundred entities seems bad programming
.
Any ideas?
Upvotes: 1
Views: 481
Reputation: 28409
You have several options. The fetch request, with fetchLimit = 1, sorted by time is actually not a bad option. You can even make the timestamp field an INDEX in the model GUI, and the lookup will be super fast.
If the database will be constantly changing, and you always want access to the most recent item, consider registering for the DidSave notification on the NSManagedObjectContext.
You can get called when the context is saved (or even when there are changes to any object). In the notification method, just look at the inserted items, and update to take the most recent value.
You can search the inserted objects, and grab the matching entity with the biggest timestamp.
The notifications for save and object change are:
NSManagedObjectContextDidSaveNotification NSManagedObjectContextObjectsDidChangeNotification
Upvotes: 1