这是一个很好的情况,您可以使用 Core Data 关系。
通常的 Apple 文档 (https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html) 会让您很好地掌握它的工作原理。
简而言之,您可以为关系指定删除规则。
在您的情况下,您可能会选择“无效”。这意味着,如果您删除该表,您的 Person 的 table-property 将变为 null,表示您的人不再坐在桌子上。
编辑:您还可以指定“级联”,这将删除人员和表格(相当无意义,但有点有趣的想法)。或者,您可以指定“拒绝”,如果至少还有一个人坐在桌子上,这将中止删除。
例子:
假设您有两个实体,“TableInfo”和“PersonInfo”。 “PersonInfo”有一个名为“table”的relationship,“TableInfo”有一个名为“persons”的relationship。 “table”是以“TableInfo”为目标的一对一关系。 “persons”是以“PersonInfo”为目标的一对多关系。
现在将“persons”的“反向关系”设置为“table”。 “表”的“反向关系”将自动设置为“人”。
如果你让 CoreData 生成你的模型子类(你应该!),你最终会得到一个像这样的类:
@interface TableInfo : NSManagedObject
@property (nonatomic, retain) NSSet *persons;
@end
@interface TableInfo (CoreDataGeneratedAccessors)
- (void)addPersonsObject:(PersonInfo *)value;
- (void)removePersonsObject:(PersonInfo *)value;
- (void)addPersons:(NSSet *)values;
- (void)removePersons:(NSSet *)values;
如您所见,CoreData 会自动为您创建适当的访问器。只需使用它们。
您现在可以执行以下操作:
TableInfo* myTable = [NSEntityDescription insertNewObjectForEntityForName:@"TableInfo" inManagedObjectContext:self.managedObjectContext];
PersonInfo* myPerson = [NSEntityDescription insertNewObjectForEntityForName:@"PersonInfo" inManagedObjectContext:self.managedObjectContext];
[myTable addPersonsObject:myPerson];
NSLog(@"%@", myPerson.table); // will be your TableInfo object "myTable"
简而言之,请阅读我上面链接的文档,那里和互联网上有很多示例。随意提出关于 SO 的问题,但对于“基本”需求,互联网上的教程将更加完整和有用。