简体   繁体   中英

NSSortDescriptor most effective way to sort Core Data NSSet objects

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM