Duck
Duck

Reputation: 35953

iPhone - fetching data on core data

I have a data structure designed like this:

employee
. department
. building
. sector
> number (this is a relationship to employeeData)



employeeData
. name
. position
. salary
> number (this is a relationship to employee)

this way, there will be only one employeeData entry per employee.

I have classes for all entities.

Now, how do I fetch every employee that matches a particular number and then the employeeData that corresponds to the employee?

what I need is this

"find employeeData for employee.number = X"

thanks

Upvotes: 1

Views: 171

Answers (1)

Jack Cox
Jack Cox

Reputation: 3300

Something like this:

NSManagedObjectContext * context  = [[NSApp delegate] managedObjectContext];
NSManagedObjectModel   * model    = [[NSApp delegate] managedObjectModel];
NSDictionary           * entities = [model entitiesByName];
NSEntityDescription    * entity   = [entities valueForKey:@"Employee"];

NSPredicate * predicate;
predicate = [NSPredicate predicateWithFormat:@"number = %@", number];


NSFetchRequest * fetch = [[NSFetchRequest alloc] init];
[fetch setEntity: entity];
[fetch setPredicate: predicate];


NSArray * results = [context executeFetchRequest:fetch error:nil];
[fetch release];

Employee *emp = [results objectAtIndex:0];
EmployeeData *data = [emp data];

Remember that the data relationship is automatically fetched due if the relationship is defined in the core data model. This was extracted and modified to fit the question from: http://www.cocoadevcentral.com/articles/000086.php

Upvotes: 3

Related Questions