gpt4 book ai didi

ios - Objective-C 函数通过在方法签名中指定关系来更新 Core Data 关系

转载 作者:行者123 更新时间:2023-11-29 04:00:29 26 4
gpt4 key购买 nike

我有各种与实体Battery存在一对多关系的核心数据实体:

Battery-----1-Many-----Comment
Battery-----1-Many-----Measurement
Battery-----1-Many-----Photo

我编写了一个很棒的函数,它可以对服务器进行极点操作,并应用关系中的更新、添加和删除。这是针对“评论”关系进行编码的,并为简洁起见进行了简单简化:

- (void)updateLocalDataWithClass:(Class)entityClass withSet:(NSSet*)existingRelationships {

NSMutableSet *entitiesToRemove = [NSMutableSet setWithSet:existingRelationships];

NSArray *serverObjects = [self getServerObjects];
for (NSMutableDictionary *serverDict in serverObjects) {

BaseEntityDO *existingEntity = [self getMatchingEntity:serverDict];
if (existingEntity) {
[existingEntity updateAttributesWithData:serverDict];
[entitiesToRemove removeObject:existingEntity];
} else {
BaseEntityDO *newEntity = [entityClass createEntity:serverDict];
[self addCommentsObject:newEntity];
}
}

[self removeBatteryComments:entitiesToRemove];
}

但是,我不想复制并粘贴此函数三次,并为每个关系稍微修改它。理想情况下,我想“将关系传递到函数中”。即告诉函数我们正在处理评论、测量或照片关系 - 并让函数使用正确的“addCommentsObject”或“addMeasurementsObject”或“addPhotosObject”。

我需要替换的两行代码是:

  1. [self addCommentsObject:newComment];
  2. [self removeBatteryComments:entitiesToRemove];

理论上,我可以用 NSSet 的单个替换来替换这两个,但我仍然需要知道我计划替换三个中的哪一个:

  1. self.batteryComments = replacementEntitySet

任何人都可以为我指明正确的方向,以便我可以优雅地为每个关系调用一次 updateLocalData 函数。

谢谢

最佳答案

您可以使用键值编码并将关系的名称作为函数的参数:

NSString *relationshipName = ...; "comments" or "measurements" or "photos"
NSMutableSet *mutableSet = [self mutableSetValueForKey:relationshipName];
[mutableSet addObject:...];
[mutableSet removeObject:...];

mutableSetValueForKey 返回一个与托管对象 self 绑定(bind)的特殊“代理对象”。这意味着如果您修改此集合(添加或删除某些内容),那么您就有效地修改了 self 的关系。

关于ios - Objective-C 函数通过在方法签名中指定关系来更新 Core Data 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15920885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com