PDA

View Full Version : Core Data, adding an object that's related to another object without the UI




Chirone
May 21, 2009, 12:07 AM
let's say in my data model i have two entities

entity1 can be related to multiple entity2 and entity2 can only be related to one instance of entity1

now.. in the UI i want to make an instance of entity1
all good.. i can do that
entity1 has a string property and i want to split that up and use them to make instances of entity2 (so when entity2 is made it has a copy of that part of the string)

what is the best way to do this?
i thought about sending a notification when the OK button is done creating an instance of entity1, but somehow i don't think that the instance of entity2 will properly be related to entity1 and thus will not be saved out..

any hints?



Chirone
May 21, 2009, 11:25 PM
in the UI i have two panels, one that represents entity1 and the other representing entity2

when entity1 is added i can assign as many entity2s as i want. which is ok, but when entity1 awakes from insert i want it to have some existing entity2s...

so in entity1's awakeFromInsert method i went something like this:

-(void)awakeFromInsert {
Entity2* anEntity = [[Entity2 alloc] init];
anEntity.properyOne = @"hello";
self.containsEntities= [self.containsEntities setByAddingObject: anEntity];
}

but the console printed out this:
2009-05-22 15:17:53.959 CoreDataTestProgram 003[25683:10b] *** -[Entity2 setPropertyOne:]: unrecognized selector sent to instance 0x1bb9f0

uh... what? this tells me that the instance of Entity2 doesn't have the ability to set propertyOne... but... it's there in the code.... :confused:

what's the proper way to programatically add an entity to the relationship?



nevermind

the answer has been here all the time:

NSManagedObjectContext* managedObjectContext = [self managedObjectContext];
self.containsEntites = [self.containsEntities setByAddingObject: [NSEntityDescription insertNewObjectForEntityForName: @"Entity2"
inManagedObjectContext: managedObjectContext]];