One-to-many relationship

  • Hi guys,

    I have just got how to set "many" relationship by using addObject:,
    but don't know how to set "one" relationship.
    I went see DepartmentAndEmploee sample, but I still don't understand.

    Would you tell me which API is the one I should use? Or I don't need
    to do anything for that?

    Entity: Employ
      name(attribute)
      department(one relationship)

    Entity: Department
      dept_name(attribute)
      employees(many relationship)

    The following code is what I wrote for a Department object adding new
    employee object.

    NSMutableSet * aSet = [deptObject mutableSetValueForKey:@"employees"];
    for (i = 0; i < maxnum; ++i )
    {
      id iEmployee = [NSEntityDescription
    insertNewObjectForEntityForName:@"Employee"
    inManagedObjectContext:context];

      [aSet addObject:iEmployee];
    }

    But how should I connect the department object to 'department' of
    Employ object.

    Is the following code OK?

    [iEmployee setValue:deptObject forKey:@"department"];

    Thank you for reading this poor explanation.

    Norio Ota
  • On Sep 26, 2007, at 10:23 PM, Norio Ota wrote:

    > But how should I connect the department object to 'department' of
    > Employ object.
    >
    > Is the following code OK?
    >
    > [iEmployee setValue:deptObject forKey:@"department"];
    >
    Yes: <http://developer.apple.com/documentation/Cocoa/Conceptual/CoreData/Articles
    /cdUsingMOs.html
    >.

    Note, though, that if you have properly modeled the inverse
    relationship you only have to set one side (that is, if you add an
    employee to the employees relationship you don't have to set the
    department relationship and vice-versa).

    "Most relationships are inherently bidirectional. Any changes made to
    the relationships between objects should maintain the integrity of the
    object graph. Provided that you have correctly modeled a relationship
    in both directions and set the inverses, modifying one end of a
    relationship automatically updates the other end—see “Manipulating
    Relationships and Object Graph Integrity”."

    mmalc
previous month september 2007 next month
MTWTFSS
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Go to today