views:

11

answers:

1

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,

+2  A: 

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).

Barry Wark
Thanks! I'll stick with what I had then; newProperty.client = self.currentClient, because it feels simpler, and it's not a response to something within a Client class or view.
GendoIkari