简体   繁体   中英

Core data with multiply relationships

I'm trying store and retrieve data using core data. I'm kind-of okay with working with dual entity's but currently trying to access an (PRC) entity which is a two levels deep.

Currently my model consists of a Fpga entity, a Session entity and an PRC entity. The Fpga entity has a one-to-many relationship to a Session entity. The Session entity has an one to one relationship to a PRC entity. The PRC entity consists of two attributes prc0 and prc1.

I'm currently populating the model from:

Fpga *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Fpga" inManagedObjectContext:self.managedObjectContext];

newEntry.name = self.fpgaTextField.text;

Session *session0 = [NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:self.managedObjectContext];
session0.type = self.s0TextField.text;

//--------
session0.prc.prc0 = [NSNumber numberWithInt:99];
session0.prc.prc1 = [NSNumber numberWithInt:113];
//--------

Session *session1 = [NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:self.managedObjectContext];
session1.type = self.s1TextField.text;

//------
session1.prc.prc0 = [NSNumber numberWithInt:[ self.p0TextField.text intValue]];;
session1.prc.prc1 = [NSNumber numberWithInt:[ self.p1TextField.text intValue]];;
//------

newEntry.session = [NSSet setWithObjects:session0, session1, nil];

And trying retrieving the PRC data like (only one object in the database for the demo):

    PRC *prc0 = (PRC*)[[[fpgaObj.session allObjects] objectAtIndex:0] prc];
    self.p0TextField.text = [NSString stringWithFormat:@"%@", prc0.prc0];

I'm always returning null but all other Fpga and Session attributes are fine. Obviously somethings wrong... but not sure what..

Thanks in advance

You do not create the PRC objects, therefore session0.prc and session1.prc are nil .

For example:

PRC *prc = [NSEntityDescription insertNewObjectForEntityForName:@"PRC" inManagedObjectContext:self.managedObjectContext];
prc.prc0 = [NSNumber numberWithInt:99];
prc.prc1 = [NSNumber numberWithInt:113];
session0.prc = prc;

Before you can do session0.prc.prc0 = ... you need to create an instance of the PRC entity. You would usually create and configure this instance and then set it as the contents of the relationship ( session0.prc = ... ). At the moment you are trying to set the numbers into a non-existent instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM