views:

37

answers:

2

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?

  1. When i insert for user entity it also inserts an address
  2. 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;
+3  A: 

No, this will not create a duplicate address. With the first insert it only creates the User, not the Address. The user's address will be nil.

If you truly did make the Address relationship of the User one-to-many, you can't assign user.address like that, it should give a warning since it's expecting an NSSet*. Also I would recommend calling it addresses. You can do:

user.address = [NSSet setWithObject:address];

or

[user addAddressObject:address];
Cory Kilger
thanks a lot, great answer. 1 question do i need to create "addAddressObject" method? or is it created by NSManagedObject? I get "may not respond to "addAddressObject"
aryaxt
It's created when you create the NSManagedObject subclass, which I assume you know how to do since you're using classes called "User" and "Address". You'll probably want to recreate those classes if you make changes to them in the model.
Cory Kilger
Also, I meant to mention this in the answer, but I'll add here that you don't really want to think about Core Data as a database with tables and rows. There are some similarities, and Core Data can even use a database to store the data, but I think the differences are significant.
Cory Kilger
A: 

CoreData is not limited to databases, it may also work in memory or using XML. Here's how things happen when you are using the sqlite store.

Core data inserts one row into the user table and one into the address table. If an address can only have one user, then it will add a column (when setting up the database) to the address table that will contain the id of the user entry. This is how the two are linked. It also does not matter how you create the link either user.address = XY; or XY.user = user;

However user.address = XY only works if users can only have one address.

Felix