Matt W.
Matt W.

Reputation: 956

Core Data Self Referencing Entity with a One-to-Many Relationship

This might be easy, but I need a little help with it.

I'm using a self-referencing entity in Core Data to set up a decision tree. Is it possible to have a one-to-many relationship on a self referencing table? Or is there a better way to set it up?

The problem that I'm running into is the parent node object is being added to the NSSet that references the child nodes, when I set the self-referencing relationship to anything but a one-to-one relationship. When I select the relationship to "To-Many", it seems to set it up as a many-to-many relationship.

I've been able to get around this by setting up a relationship that is one-to-one, and a separate relationship that is many-to-many, then setting the one-to-one relationship as the parent node, but I'm not able to set the reverse relationships. And not setting the reverse relationship, I'm getting a compiler warning.

Any thoughts and ideas are greatly appreciated!

Upvotes: 1

Views: 1880

Answers (2)

adonoho
adonoho

Reputation: 4339

Matt W,

First, do not fight with Core Data. You will lose.

Second, please show some code. I suspect you may not be using the relations the way you think you are.

Third, as I was interested in your problem, I wrote a trivial example of your tree. Here is some code:

The self-referential class:

@interface ToMany : NSManagedObject

@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSSet *children;
@property (nonatomic, retain) ToMany *parent;
@end

Code that uses the class without any compiler errors:

ToMany *parent = [NSEntityDescription insertNewObjectForEntityForName: kToManyEntity 
                                               inManagedObjectContext: self.managedObjectContext];
parent.date = NSDate.date;

ToMany *child1 = [NSEntityDescription insertNewObjectForEntityForName: kToManyEntity 
                                               inManagedObjectContext: self.managedObjectContext];
child1.date   = parent.date;
child1.parent = parent;

ToMany *child2 = [NSEntityDescription insertNewObjectForEntityForName: kToManyEntity 
                                               inManagedObjectContext: self.managedObjectContext];
child2.date   = parent.date;
child2.parent = parent;

I think I've implemented your description of the problem. What, exactly, are you concerned about?

Andrew

Upvotes: 2

Mundi
Mundi

Reputation: 80273

I think your setup with one-to-one for the parent is good. However, the children should be one-to-many, right? Logically, each of these these two relationships are each other's reverse relationship. You should be able to select them in the data model editor in Xcode.

Upvotes: 0

Related Questions