Reputation: 453
I have two Objective-C Core Data entities - say Person and Nationality. Person would have a To-One relationship with Nationality, whilst Nationality would have a To-Many relationship with Person. Also, Person class can have any number of objects / rows, whereas Nationality would have a pre-defined list of 200 odd instances. So Person should not be able to assign a nationality to itself other than those 200 objects.
Can someone advise please how would we code this out or in case there is a sample code available? Afraid I dont seem to be able to get a start on how to leverage setValue: forKey: here...
Much appreciated!
Upvotes: 2
Views: 323
Reputation: 28419
Let's assume that your Nationality entity has a "name" attribute that uniquely identifies that nationality. You can provide any manner of UI to get this from the user. It can be typing in a string or fetching all nationalities and putting them in a table or some kind of picker.
If you want all nationalities, that's easy.
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Nationality"];
NSError *error;
NSArray *nationalities = [moc executeFetchRequest:fetchRequest error:&error];
if (nationalities == nil) {
// handle error
} else {
// You now have an array of all Nationality entities that can be used
// in some UI element to allow a specific one to be picked
}
If you want to look it up based on a string for the name...
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Nationality"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name = %@", nationalityName];
fetchRequest.fetchLimit = 1;
NSArray *nationalities = [moc executeFetchRequest:fetchRequest error:&error];
if (nationalities == nil) {
// handle error
} else {
NSManagedObject *nationality = [nationalities firstObject];
// If non-nil, it will be the nationality object you desire
}
Creating the person and assigning its nationality is also straight forward...
if (nationality) {
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:moc];
// Set any attributes of the Person entity
[person setValue:@"Fred Flintstone" forKey:@"name"];
// Assign its nationality, and as long as the relationship is setup with
// inverse relationships, the inverse will be automatically assigned
[person setValue:nationality forKey:@"nationality"];
}
Upvotes: 1