Reputation: 4843
I have various Core Data entities in a one-to-many relationship with the entity Battery
:
Battery-----1-Many-----Comment
Battery-----1-Many-----Measurement
Battery-----1-Many-----Photo
I have written an awesome function which poles the server and applies updates, addition and deletions from the relationship. Here it is, coded for the "Comments" relationship, and simplified very lightly for brevity:
- (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];
}
However, I don't want to have to copy and paste this function three times, slightly modifying it for each relationship. Ideally, I'd like to "pass the relationship into the function". i.e. The tell the function that we're dealing with either the Comments, Measurements or Photos relationship - and for the function to use the correct "addCommentsObject" or "addMeasurementsObject" or "addPhotosObject".
The two lines of code I need to replace are:
[self addCommentsObject:newComment];
[self removeBatteryComments:entitiesToRemove];
In theory I could replace these two with a single replacement of the NSSet, but I would still need to know which set of the three I'm planning to replace:
self.batteryComments = replacementEntitySet
Can anyone point me in the right direction so I can elegantly call my updateLocalData
function once per relationship.
Thanks
Upvotes: 0
Views: 118
Reputation: 539745
You can use Key-Value coding and make the name of the relationship a parameter of your function:
NSString *relationshipName = ...; "comments" or "measurements" or "photos"
NSMutableSet *mutableSet = [self mutableSetValueForKey:relationshipName];
[mutableSet addObject:...];
[mutableSet removeObject:...];
mutableSetValueForKey
returns a special "proxy object" that is tied to the managed object self
. That means if you modify this set (add or remove something) then you effectively modify the relationship of self
.
Upvotes: 1