Reputation: 12335
So I have two core data entities - PersonObj
, and CheckInObj
.
Each account has multiple persons. Each person can have multiple checkins, and each checkin has a timestamp.
PersonObj {
NSSet * checkIns;
}
CheckInObj {
NSDate *timestamp
}
The goal is to sort the all the persons by most recent checkin.
NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
NSArray *sortedCheckins = [person.checkIns sortedArrayUsingDescriptors:@[nameDescriptor]];
CheckInObject *mostRecentCheckin = [sortedMessages lastObject];
This gives me the most recent check in.
I can now proceed to sort have a temp cache which has the most recent checkin data which I found vs that corresponding person, and use that to sort each person, and finally have a sorted list of persons.
Question is:
Can I somehow run this on a Person's object directly?
NSArray *persons = [account.persons allObjects];
Instead of
for (Person *person in persons) {
// find most recent checkin, save temp cache, and resort each time we see a new person in the loop
}
Can I construct an awesome sort descriptor which can do this for me?
I tried.
[NSSortDescriptor sortDescriptorWithKey:@"checkIns.timestamp" ascending:YES];
But it wont compare it since its an NSSet.
Any thoughts?
Upvotes: 0
Views: 290
Reputation: 16660
You cannot do it that way, because you would need an aggregate. I. e. running checkIns.timestamp
on persons does not declare, if you want to get the first or last check-in. (Or the average or whatever.) Beside this -sortDescriptorWithKey
takes a key, not a key path.
However, typically you can solve that with a computed property of Person
lastCheckIn
. It depends on your concrete situation, but you can recalculate that property every time the checkIns
array is changed (with a single comparison) or calculate it on demand, if someone tries to retrieve it.
Upvotes: 2