Coredata relationship tutorial? Adding/finding objects that belong to something?
Anyone have a link to a coredata relationship tutorial for basic create,retrieve,update,delete type operations?
I have two entities set up, entity A and entity B.
I have the relationships and inverse relationships set up between A and B.
A can have many B. B can have only one A.
Basically the tasks I nee开发者_运维技巧d to do:
1) When adding B to A, I need to make sure if B doesn't already exist in A (how can I test this?) 2) How do you create B and then save it to A?
TIA
You probably have a NSSet* in A, but you have an A* attribute in B. (A has many B, B has one A).
A* a = [NSEntityDescription insertNewObjectForEntityForName:@"A" inManagedObjectContext:moc];
B* b = [NSEntityDescription insertNewObjectForEntityForName:@"B" inManagedObjectContext:moc];
B.hasA = A;
When you add B to an A the relationship is stored in a set. By definition you have only one instance of that B in A. I don't think you need to worry about making sure it is not already there. If you want to you could do a fetch of all entity B where part of the predicate is "hasA = A" and the second part will be a check against something uniquely identifying your B objects, such as a unique key.
You'll find Core Data takes care of the other side of the relationship, i.e. adding the B to A's NSSet.
精彩评论