Reputation: 13
I am working on a simple Core Data app. I have two classes: Client
and Home
. There is a one-to-many relationship between Clients and Homes (i.e., a Client can have many Homes. Among other attributes, the Home
class has one called purchaseDate
.
I am trying to write two methods on the Client
class: -homesByDate
and -firstHome
. -homesByDate
should return either an NSArray or NSSet of the client's homes sorted by purchaseDate
. -firstHome
should return just the first home that the client purchased.
I know that given a Client, I can use self.homes
to access all of the client's homes, but how do I implement the methods above? Does this involve applying some sort of an NSPredicate?
Help! Thanks!
Upvotes: 0
Views: 60
Reputation: 14824
You seek NSSortDescriptor
!
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"purchaseDate" ascending:YES];
//Obtain arrayOfHomes however you'd like
homesByDate = [arrayOfHomes sortedArrayUsingSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
firstHome = [homesByDate objectAtIndex:0];
I should also point out that it's common to let NSArrayController do the sorting for you (if, for example, homesByDate
is just for display in a table view or something). You can use setSortDescriptors
or use bindings. (This is also handy if you want the user to be able to choose from several orders.)
Upvotes: 2