【发布时间】:2011-09-13 04:46:31
【问题描述】:
假设我有一个自定义 NSManagedObject Department,它有一个属性表示与员工的一对多关系,即NSSet *employees;。
对于给定的部门,我想删除员工中的所有个对象。请问推荐/最好的方法是什么?
因此,假设我的代码如下所示:
Department.h
@interface Department: NSManagedObject {
}
@property (retain) NSString *departmentName;
@property (retain) NSSet *employees;
@end
Department.m
@implementation Department
@dynamic departmentName;
@dynamic employees;
Employee.h
@interface Employee: NSManagedObject {
}
@property (retain) NSString *firstName;
@property (retain) NSString *lastName;
@property (retain) Department *worksIn;
@end
doCoreDataStuff
- (void)doCoreDataStuff:sender {
//add a department, give it a couple employees, then try to remove those employees
NSEntityDescription *deptEntity = [NSEntityDescription entityForName:@"Department"
inManagedObjectContext:self.managedObjectContext];
Department *dept = [Department alloc] initWithEntity:deptEntity
insertIntoManagedObjectContext:self.managedObjectContext];
NSError *error;
dept.departmentName = @"Accounting";
//save more often than normal to see more easily what causes error
if (![self.managedObjectContext save:&error]) NSLog(@"\nError: %@", [error localizedDescription]);
NSEntityDescription *empEntity = [NSEntityDescription entityForName:@"Employee"
inManagedObjectContext:self.managedObjectContext];
emp.firstName = @"Steve";
emp.lastName = @"Smith";
emp.worksIn = dept;
if (![self.managedObjectContext save:&error]) NSLog(@"\nError: %@", [error localizedDescription]);
emp = [[Employee alloc] initWithEntity:empEntity
insertIntoManagedObjectContext:self.managedObjectContext];
emp.firstName = @"Natasha";
emp.lastName = @"Johnson";
emp.worksIn = dept;
if (![self.managedObjectContext save:&error]) NSLog(@"\nError: %@", [error localizedDescription]);
//all good so far! now will try to delete all employees for this department
dept.employees = [NSSet set];
if (![self.managedObjectContext save:&error]) NSLog(@"\nError: %@", [error localizedDescription]); //"Multiple validation errors occurred."
//this also produces the same error
[[dept mutableSetValueForKey:@"employees"] removeAllObjects];
if (![self.managedObjectContext save:&error]) NSLog(@"\nError: %@", [error localizedDescription]); //"Multiple validation errors occurred."
employees 关系不是可选的,所以我猜测从部门中删除员工意味着我试图“孤立”员工,即在没有关联部门的情况下将员工保留在持久模型中。
所以,我认为我最初的问题应该改写为:当孩子与父母有非可选关系时,删除“父母”的所有“孩子”对象的最佳/推荐方法是什么?
我怀疑答案将是“循环并一次删除一个员工对象”。
更新
根据答案和指向 Apple 文档的链接,我应该能够将删除规则设置为“级联”,然后像 department.employees = [NSSet set]; 这样的代码将起作用。但是,这在我已相应设置删除规则的非常简单的项目中不起作用。
谢谢
【问题讨论】:
-
我想知道您是否找到了解决该问题的方法?我有同样的问题..坚持你的例子我有一个同步过程,我试图删除所有员工,然后从头开始创建它们(不要让我的同步太复杂)..但目前唯一的方法我得到的工作是消除双方的“多”关系 - 迭代调用 [managedObjectContext deleteObject:employee] 的员工,然后执行 [[department mutableSetValueForKey:@"employees"] removeAllObjects];这似乎是错误的,但有效..
-
我从来没有让上面的例子工作。最后,我遍历了员工并删除了他们,如下面的回复中我刚刚接受了答案
-
您误解了文档。当您删除部门对象时,删除规则将应用于员工集中的员工对象。更改关系不会删除任何对象。
标签: objective-c cocoa macos core-data