Anders
Anders

Reputation: 2941

Get all objects that belongs to a entity in a one-to-many relationship with core data

I'm working on simple iPhone app and I'm trying to get core data working. I currently have two entities in my data model, it looks like this:

Data relationsship

In my application I have a tableview that should display all pages that belongs to a certain note block. I currently use:

NoteblockAppController * appController = [NoteblockAppController sharedNoteblockAppController];
NSArray * list = [appController allInstancesOf:@"Page" orderBy:@"createdAt"];
noteblockPages = [list mutableCopy];

But this obviously doesn't work since it always shows the same pages. I assume that I have to fetch the result some other way, but I don't know how.

I'm quite stuck so any tips/tricks would be great.

Thanks.

Upvotes: 2

Views: 435

Answers (2)

bshirley
bshirley

Reputation: 8357

I like to add derived methods to access things like this. I add these to the custom class but don't model them in the data model.

Once you get your accessor working correctly, it should return a mutable set. Then:

- (NSArray *)noteblockPagesArray {
  NSMutableSet *pages = self.noteblockPages;
  NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:YES];

  NSArray *orderedPages = [pages sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
  return orderedPages;
}

Modify to cache value as appropriate/needed.

Upvotes: 1

picciano
picciano

Reputation: 22701

Let CoreData do the work. You have an instance of the Noteblock, correct?

[yourNoteblock noteblockPages]

Upvotes: 1

Related Questions