I have 2 entities : User, Address.
I have set the relationship each User can have many “Address”.
I am not sure how core data works but from my understanding, every time i call insertEntityForName it creates and stores an object. (also a row in table)
So the question:
Doesn’t the following code store a duplicate address in core data?
- When i insert for user entity it
also inserts an address - When i call insert for address
entity it creates another address.
If i am correct and this actually creates a duplicate in the database what is the way to prevent it?
User *user = [NSEntityDescription insertEntityForName:@"User"
inManagedObjectContext:self.managedObjectContext];
user.firstName = @"first name";
user.lastName = @"last name";
Address *address = [NSEntityDescription insertEntityForName:@"Address"
inManagedObjectContext:self.managedObjectContext];
address.street = @"street";
user.address = address;
No, this will not create a duplicate address. With the first insert it only creates the
User, not theAddress. The user’s address will be nil.If you truly did make the
Addressrelationship of the User one-to-many, you can’t assignuser.addresslike that, it should give a warning since it’s expecting anNSSet*. Also I would recommend calling itaddresses. You can do:or