xcode iOS CoreData simple relational data retrieval

I have two tables in my coredata model (have more but keeping the example simple) employees and departments. An employee belongs in a department and a department contains many employees. Here are the table definitions:

Employee
================
employeeID int32
firstName string
lastName string
departmentID int32

Department
================
departmentID int32
departmentName string

Im just wondering what is the cleanest way to retrieve all Employees and their departmentName?

Thanks

Answers


You seem to be designing your schema as if it was a database. Please do not do this. It is not necessary and antithetical to how CoreData works. You should get rid of your ID fields. Simply declare the appropriate relationships in the model and then all you have to do to get the department for an employee would be:

myEmployee.departmentName

Fetching all of the employees would just be done like this:

NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
    entityForName:@"Employee" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
    initWithKey:@"firstName" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
    // Deal with error...
}

This was taken from the docs. If you are using ARC then change the code accordingly.


Need Your Help

Mock a model method in Django

django unit-testing django-models django-testing django-tests

I'm just getting started with Mock for testing Django apps without touching the db. I can successfully mock my model objects in my tests, but I'm a little confused as to how to deal with model meth...

Kill bash and child process

c linux bash signals

My C program executes commands in a bash shell. To do this, I fork and in the child process I run: