Matt Gomes
Matt Gomes

Reputation: 91

Objective-C Core Data: Access data from child of child

I'm slowly figuring out Core Data for my iPad app, but I just can't seem to figure out how to access data from my to-many children (who also have to-many children). I'm hoping to get some code examples from the experts here.

Let's use a simple data structure: Parent -(to many)-> Child -(to many)-> Toy

I can fetch the Parent just fine and get it's data and the NSSet of children. After that, I get lost.

1) What would the code look like to get the data from a Child (say, get a specific Child's age or ALL the children's ages in the NSSet?

2) How would I then get the NSSet of the Toys a specific Child has? (also assuming accessing the Toy data would be the same as #1 code).

I sincerely appreciate the help! This is supposed to be EASIER... isn't it?

Thanks!

Upvotes: 1

Views: 1097

Answers (2)

deanWombourne
deanWombourne

Reputation: 38475

If this line :

NSSet *children = [parent children];

gets you an NSSet of child objects then

NSManagedObject *child = [[parent children] anyObject];

should get you a (random) Child object. From this object you should just be able to do

NSNumber *age = [child age];
NSSet *toys = [child toys];

or have I missed something in the question?

Upvotes: 1

user23743
user23743

Reputation:

1) All the childrens' ages: NSSet *ages = [parent.children valueForKey: @"age"];

To get a particular child you need to specify that child. You could just use [parent.children anyObject] but it's likely you care which answer you get, in which case you can filter the set. Check out the NSSet documentation, specifically the filteredSetUsingPredicate method.

2) Having got your specific child, you just ask for its toys property.

Easier than what?

Upvotes: 2

Related Questions