views:

506

answers:

4

Hi,

I have a tableview with recipe. The user can add and remove recipe. When a recipe is clicked, another tableview is pushed, and display the ingredients. Same here, the user can add and remove ingredients.

There is a oneToMany relationship between recipe and ingredients.

Here is my challenge:

I want to display the number of ingredient in the recipe tableview row. I know how to set it all up in interface builder with the rows, but I dont know how to get the count of ingredient for a single recipe.

Is this even possible to do?

Thanks in advance!

A: 

Just do a fetch for all the ingredients, with a predicate that allows all matches. This NSFetchRequest will return an NSArray, when executed. Just do a [myArray count] to get the number of ingredients.

Alex Reynolds
Isnt that too much work ( object creation ect) just for getting the count ?
Surya
Perhaps there are other ways to get to the data store without creating any objects. Please post alternatives. I'm curious myself.
Alex Reynolds
Actually, here's a SO question on the very subject: http://stackoverflow.com/questions/1134289/cocoa-coredata-effiecient-way-to-count-entities
Alex Reynolds
Since the Recipe object is already in memory, the easiest path is to ask the relationship for its count as mentioned by Helephant above.
Marcus S. Zarra
A: 

Thanks for reply. How would I do the fetch request?

I have one fetch request in the beginning to get all the recipe. Then I have another in the IngredientViewController.

So I kind have all the information I need. The challenge is to get the count from the IngredientViewController to the RecipeViewController, and simultaneously make sure that that count is places in the corresponding row.

I guess I need to make all this happen in the cellForRowAtIndexPath, in the rootView (RecipeViewController)? But I can't figure it out yet?

thanks in advance

James
+3  A: 

Use countForFetchRequest instead of executeFetchRequest and (for SQL backed stores) it will do a COUNT instead of a SELECT.

Ken Aspeslagh
+2  A: 

If you are using core data you can just ask the ingredients list how many ingredients it has inside it by calling the count method:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    int count = [recipe.ingredients count];
    return count;
}

You can find out what properties and methods the collection class has by looking at the NSSet class in the documentation.

I found out what class to look at by looking at the generated class that core data creates:

@class ParentObject;
@interface ParentObject :  NSManagedObject  
{
}
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet* childObjects;
@end
Helephant
Since the OP already has the recipe object this is the easiest answer.
Marcus S. Zarra