views:

41

answers:

2

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!

A: 

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?

deanWombourne
+1  A: 

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?

Graham Lee
Easier than... SQLlite or a flat database? Thanks for the help!
Matt Gomes
Would [parent.child anyObject] return an NSManaged object or a Child object?
Matt Gomes
@Matt: depends on your managed object model. By default it'll be an NSManagedObject.
Graham Lee