Reputation: 4797
I have tried to find apple documentation/tutorials out there on how to let a user dynamically add an object and apply the necessary relationship, but need some help with what tutorials are good or what apple documentation will help.
An example of my Core Data problem: 2 Entities of Photographer
and Photo
, where there is a 1-to-Many relationship between a Photographer
and Photo
. When the user adds a Photo
, I need to be able to specify which Photographer
took that Photo
.
Upvotes: 1
Views: 3093
Reputation: 3751
So first you'll create a new entity for photo:
NSManagedObject *photoObject = [NSEntityDescription
insertNewObjectForEntityForName:[entity name]
inManagedObjectContext:context];
The NSManagedObject can be replaced with your Photo object or w/e if you have a subclass made. You will set all the attributes for it. To set the photographer you will set it as you would any other attribute. If you don't have a reference for the Photographer, you can query it like this:
NSFetchRequest *query = [[NSFetchRequest alloc] initWithEntityName:@"Photographer"];
[query setPredicate:[NSPredicate predicateWithFormat:@"id == %@", photographerId]];
NSArray *queryResults = [context executeFetchRequest:bcQuery error:&error];
Your query result will have the photographer object. You can then set it on your photoObject as any other attribute and the link will be created automatically.
[photoObject setPhotographer:[queryResults objectAtIndex:0]];
or if you are using NSManagedObject:
[photoObject setValue:[queryResults objectAtIndex:0] forKey:@"photographer"];
The cool thing with CoreData is that it is relational. You can't really think of it as a typical DBMS. You create object and set relationships between them in a very object-oriented way. There is not primary-key/foreign-key to take care of, that is all done in the background by CoreData.
EDIT:
You can choose to create a subclass of NSManagedObject to more easily access attributes and relationships for your entity. Make sure to specify this subclass in the CoreData model explorer; in the sidebar, you will change the "class" field to your new subclass.
Here is an example of a NSManagedObject subclass:
//Interface
@interface Photo : NSManagedObject
#pragma mark - Attributes
@property (nonatomic, strong) NSNumber *id;
@property (nonatomic, strong) NSString *name;
#pragma mark - Relationships
@property (nonatomic, strong) NSSet *someToManyRelationship;
@property (nonatomic, strong) Photographer *photographer;
@end
//Implementation
@implementation Photo
@dynamic id, name;
@dynamic someToManyRelationship, photographer;
@end
Hope this helps!
Upvotes: 5