我有一个与其他实体电子邮件地址,电话有一对多关系的联系人实体。
这种关系(称为"电子邮件,电话"自然而然)也是有序的,这样我就可以在表格视图中显示联系人的电子邮件地址列表,并允许用户删除或修改每一个。据我所知,需要对它们进行排序,以便我可以判断哪一个被删除/修改:例如,如果用户点击第1行中的删除按钮,则应该从关系中删除第二个电子邮件地址。没有订购,我也不知道要删除哪一个。
生成NSManagedObject子类时,我在类上获得了一个NSOrderedSet属性,而CoreData在.h文件中提供了一些访问器:
@interface Contact (CoreDataGeneratedAccessors)
- (void)insertObject:(PLEmail *)value inEmailsAtIndex:(NSUInteger)idx;
- (void)removeObjectFromEmailsAtIndex:(NSUInteger)idx;
- (void)insertEmails:(NSArray<PLEmail *> *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeEmailsAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInEmailsAtIndex:(NSUInteger)idx withObject:(PLEmail *)value;
- (void)replaceEmailsAtIndexes:(NSIndexSet *)indexes withEmails:(NSArray<PLEmail *> *)values;
- (void)addEmailsObject:(PLEmail *)value;
- (void)removeEmailsObject:(PLEmail *)value;
- (void)addEmails:(NSOrderedSet<PLEmail *> *)values;
- (void)removeEmails:(NSOrderedSet<PLEmail *> *)values;
- (void)insertObject:(PLTelephone *)value inTelephonesAtIndex:(NSUInteger)idx;
- (void)removeObjectFromTelephonesAtIndex:(NSUInteger)idx;
- (void)insertTelephones:(NSArray<PLTelephone *> *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeTelephonesAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInTelephonesAtIndex:(NSUInteger)idx withObject:(PLTelephone *)value;
- (void)replaceTelephonesAtIndexes:(NSIndexSet *)indexes withTelephones:(NSArray<PLTelephone *> *)values;
- (void)addTelephonesObject:(PLTelephone *)value;
- (void)removeTelephonesObject:(PLTelephone *)value;
- (void)addTelephones:(NSOrderedSet<PLTelephone *> *)values;
- (void)removeTelephones:(NSOrderedSet<PLTelephone *> *)values;
@end
我的问题是,是否有任何方法可以使此代码通用,因此应删除isKindOfClass
检查:
NSArray *nestedArray = [orderedSet array];
id nestedObject = [nestedArray objectAtIndex:indexPath.row];
if ([nestedObject isKindOfClass:[PLEmail class]]) {
PLEmail *email = (PLEmail *)nestedObject;
[email MR_deleteEntity];
[self.contact removeEmailsObject:email];
}
else if ([nestedObject isKindOfClass:[PLTelephone class]]) {
PLTelephone *telePhone = (PLTelephone *)nestedObject;
[email MR_deleteEntity];
[self.contact removeTelephonesObject:telePhone];
}
答案 0 :(得分:2)
如果您有互惠关系(按照建议),您可以在电子邮件或电话实体上取消联系关系。这也将从联系人列表中删除该实体。
处理多种关系的示例代码
- (void)removeRelationship:(NSString *)relationshipKeyPath fromEntity:(NSManagedObject *)entity {
[entity setValue:nil forKeyPath:relationshipKeyPath];
}
你会像这样使用它:
[self removeRelationship:@"contact" fromEntity:unknownRelationshipForContact];