views:

61

answers:

3

Hello,

Supposing you had a Core Data relationship such as:

Book ---->> Chapter ---->> Page

Given a Book object called aBook, aBook.chapters will return the book's chapters. But how do you get a book's pages (i.e. book.pages)? And how would you get the pages sorted by a pageNumber property?

Thank you!

+2  A: 

Given a Book instance, myBook:

NSSet* pages = [myBook valueForKeyPath:@"[email protected]"];

will give you the union of all pages. See the "Set and Array Operators" section in the Key-Value Coding Programming guide.

NSArray *chaperPages = [myBook.chapters valueForKeyPath:@"pages"];

will give you an array of NSSets of pages, one set per chapter.

Barry Wark
A: 

@Barry -- so those will span Core Data relationships? Where is this all explained in a coherent way?

Wilhelm VonScharrtenburg
The Key-Value Coding Programming Guide mentioned above covers things like key paths. You might also want to look at the Core Data Programming Guide if you have specific Core Data questions.
theMikeSwan
@Wilhelm, Core Data is definitely an "advanced" Cocoa topic. Start by learning the standard Cocoa object model, then Key-Value Coding. Core Data `NSManagedObject` instances are Key-Value Coding compliant. So yes, my answer above will work across the Core Data relationships exposed by the managed objects.
Barry Wark
so to expand on this a bit, what would the code look like if the OP had wanted all of a `Book`'s `Page`s with `pageNumber > 20`?
Wilhelm VonScharrtenburg
@Wilhelm in that case the easiest thing to do would be to set-up a fetch request where `Book` == myBook and pageNumber > 20.
theMikeSwan
A: 

The quickest way to get all Pages of a Book (myBook) sorted by pageNumber would be:

NSSet *pageSet = [myBook valueForKey:@"[email protected]"];
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey@"pageNumber" ascending:YES];
NSArray *pages = [pageSet sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
[sortDesc release];

This will yield an array with all pages from all chapters sorted by pageNumber

theMikeSwan