James
James

Reputation:

Get number of objects in a Core Data relationship

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.

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 possible?

Upvotes: 5

Views: 3934

Answers (3)

Helephant
Helephant

Reputation: 17028

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

Upvotes: 10

Ken Aspeslagh
Ken Aspeslagh

Reputation: 11594

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

Upvotes: 12

Alex Reynolds
Alex Reynolds

Reputation: 97004

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.

Upvotes: 1

Related Questions