我有以下基本问题:CoreData - 为现有实体添加新关系
我有两个实体,人员和部门。
在添加新人之前,我想检查部门是否已经存在,如果有,请将新人员链接到现有部门。
简单的插入一个新的部门关系:
Department *department = (Department *)[NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
department.groupName = @"Office of Personnel Management";
Person *person1 = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
person1.name = @"John Smith";
person1.birthday = [self dateFromString:@"12-1-1901"];
person1.department = department;
Person *person2 = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
person2.name = @"Jane Doe";
person2.birthday = [self dateFromString:@"4-13-1922"];
person2.department = department;
department.manager = person1;
department.members = [NSSet setWithObjects:person1, person2, nil];
的最后一行,使联动 - 这是确定。
但如果我要做到以下几点,上面的代码执行后什么:
[self checkForExistingDepartment:@"Office of Personnel Management"];
if(self.existingDepartment) {
// here is my Problem number 1:
// department = ???
(NSEntityDescription *) department = self.existingDepartment;
} else {
Department *department = (Department *)[NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
department.groupName = @"Office of Personnel Management";
}
Person *person1 = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
person1.name = @"John Smith the second one";
person1.birthday = [self dateFromString:@"12-1-1901"];
person1.department = department;
// former line for adding new: department.members = [NSSet setWithObjects:person1, nil];
// and here is my problem number 2:
// I think I need something like: [NSSet addObjects:person1, nil];
总之形式我的问题是重复的表项部门。
也许有人知道一个好的CoreData教程,这对于初学者来说具有先进的SQL知识。 (搜索谷歌或阅读开发文档数小时是没有那么有用,因为我认为:))
对于我作为一个初学者,现在是否很重要,无论我是否正确的方式,是否有人可以证实这一点?
感谢和问候,
马蒂亚斯