Is it is mandatory to store both entities data when storing in core data?

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]);
}

Answers


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 category entity and set its relationship randomrelation in 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. Category instead of category, and adopt the camel case notation.

Second, create an inverse relationships from Brandom to Category. Inverse rels allow you to maintain the graph consistency. In your model Category has a to-many rel to Brandom declared as Optional and Brandom has an inverse and non-Optional rel (one-to-one) to Category. This allows you to create a Category with zero or more Brandom but a Brandom cannot "live" without a Category.

Hope that helps.


Need Your Help

Refused to set unsafe header "Cookie" error in browser yet request is successful

javascript angularjs

I'm using Angularjs. When I set Cookie header with xhr.setRequestHeader() I get the following error on Chrome:

How can I sort the output of 'ls' by last modified date?

linux unix shell ls

How can I sort the output of ls by last modified date?