【发布时间】:2011-02-15 15:04:03
【问题描述】:
我有以下基本问题:
我有两个实体,个人和部门。
在添加新人之前,我要检查该部门是否已存在,如果存在,则将新人链接到现有部门。
带有新部门关系的简单插入:
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 知识的初学者。 (在谷歌上搜索或阅读开发者文档几个小时并没有我想的那么有用:))
对于作为初学者的我来说,重要的是现在我是否走在正确的道路上,有人可以确认这一点吗?
谢谢你,
马蒂亚斯
【问题讨论】:
标签: iphone core-data relationship