开发者

What is the Proper way to create new to-many relationship in CoreData?

I have an entity called "Client," and each Client can have multiple "Properties." CoreData creates methods on the Client class for me for adding a new Property to the set, but I don't understand the 开发者_高级运维purpose of this. Is there any difference at all between:

Property *newProperty = [NSEntityDescription insertNewObjectForEntityForName:@"Property" inManagedObjectContext:self.managedObjectContext];
newProperty.name = @"[New Property]";
newProperty.client = self.currentClient;

and this:

Property *newProperty = [NSEntityDescription insertNewObjectForEntityForName:@"Property" inManagedObjectContext:self.managedObjectContext];
newProperty.name = @"[New Property]";
[self.currentClient addPropertiesObject:newProperty];

As far as I can tell, both of these do the exact same thing; they just associate my new Property with the correct Client. Is one preferred over the other; is there any difference at all? I just want to make sure that I'm not missing the entire point of the automatically generated "addPropertiesObject" method. Thanks,


Assuming the relationship is bi-directional (i.e. the inverse relationship is defined from both sides), then there is no functional difference between the examples you present. Use whichever makes most sense in your code. If you are focussed on the Property, use -[Property setClient:]. Similarly, use -[Client addPropertiesObject:] if your code feels focussed on the Client.

For completeness, you can also use

Client *client = ...
Property *property = ...
[[client mutableSetValueForKey:@"properties"] addObject:property];

which makes use of the mutable proxy for the to-many relationship, used in Key-Value Coding. This last option should probably be avoided in favor of the explicit methods above, as Core Data might optimize those methods (an implementation detail; I don't know if this is the case).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜