I am creating a Core Data application where:
category entity has the following attributes
catid:int
catname:string
randomrelation:to-many rel to brandom entity
brandom is another entity having attributes
cid:category entity
no:int
arr:int
My code is the following
category *c=[NSEntityDescription insertNewObjectForEntityForName:@"category" inManagedObjectContext:context];
for (int i=0; i<[arrayofnumbers count]; i++) {
brandom *r=[NSEntityDescription insertNewObjectForEntityForName:@"brandom" inManagedObjectContext:context];
c.catid=[NSNumber numberWithInt:i];
r.cid=c;
r.no=[NSNumber numberWithInt:i+1];
int objectatindex=[[arrayofnumbers objectAtIndex:i] intValue];
NSLog(@"object at index:%i",objectatindex);
r.arr=[NSNumber numberWithInt:objectatindex];
[set addObject:r];
}
c.randomrelation=r;
NSLog(@"set element count=%i",[set count]);
if (![context save:&error]) {
NSLog(@"%@",[error localizedDescription]);
}
I’m not pretty sure if I understood your question.
About your title question, if you are asking if it is mandatory to store data for different etities that are linked with a relatiosnhip, the answer is it depends.
You could do that in different times within your application lifecycle if the properties (the relationship) has been declared as optional (1) or you must set them at the same time if you declared is as non-optional (2).
So, if in the first case (1) if could set you create the
categoryentity and set its relationshiprandomrelationin a different time. In the second one (2), you need to set both in the same time, since Core Data will give a consistency error.Some notes about your model.
First call the enities like class name, e.g.
Categoryinstead ofcategory, and adopt the camel case notation.Second, create an inverse relationships from
BrandomtoCategory. Inverse rels allow you to maintain the graph consistency. In your modelCategoryhas a to-many rel toBrandomdeclared as Optional andBrandomhas an inverse and non-Optional rel (one-to-one) toCategory. This allows you to create aCategorywith zero or moreBrandombut aBrandomcannot “live” without aCategory.Hope that helps.