开发者

How to get address the object of an related entity with CoreData?

Ok, after I ran into a dead end modifieing an existing Apple example for CoreData, I started completely new creating my own project and that worked fine,..... until I tried to access a related entity.

So here is what I did.

I created 2 entities, where one is just the detail information of the other one, so there is a one-2-one relationship.

Entity #1, Stocks:

  • name
  • value
  • details --> relationship to Entity #2

Entity #2, StockDetails:

  • bank
  • published
  • stock --> relationship to Entity #1

Now, I created the "Managed Object Class" for both of the Entities.

Then I created a few lines to put some data into it

NSManagedObjectContext *context = [self managedObjectContext];

S开发者_StackOverflow中文版tocks *stockinfo= [NSEntityDescription
    insertNewObjectForEntityForName:@"Stocks" 
    inManagedObjectContext:context];
stockinfo.name = @"Apple";
stockinfo.value = [NSNumber numberWithInt:200];


StockDetails *thestockdetails = [NSEntityDescription
    insertNewObjectForEntityForName:@"StockDetails" 
    inManagedObjectContext:context];

thestockdetails.bank = @"Bank of America";
thestockdetails.published = [NSDate date];
thestockdetails.stock = stocks_;

stockinfo.details = thestockdetails ;

NSError *error;
if (![context save:&error])
{
    NSLog(@"A Problem occured, couldn't save: %@", [error localizedDescription]);
}

Just want to mention here, that I do not get an error with this.

Next I put everything into a UITableViewController for a preview and another for a detail view. The preview just shows infos form Entity #1 (Stocks) and when selected it shows the detail view.

Now here I also display the infos form Entity #1 (Stocks) but I want to show the Entity #2 (StockDetails) aswell.

This is how I try to access the data :

StockDetails *details_ = [stockinfo details];

And this gives me a EXC_BAD_ACCESS.

So any idea what I am doing wrong here ?

Thanks


There is nothing wrong with

StockDetails *details_ = [stockinfo details];

You should look if you do not accidently release details or stockinfo somewhere. Since you have this in a UITableViewController, the object could be used for every row/section.


For a one-to-one relationship, this should work:

StockDetails *details = [stockinfo valueForKey:@"details"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜