Samantha Baxton
Samantha Baxton

Reputation: 13

Core Data - How to get related records through a join table

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!

Upvotes: 1

Views: 1488

Answers (2)

theMikeSwan
theMikeSwan

Reputation: 4729

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

Upvotes: 0

Barry Wark
Barry Wark

Reputation: 107754

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.

Upvotes: 2

Related Questions