Skip to content

Instantly share code, notes, and snippets.

@jpmhouston
Created September 15, 2014 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmhouston/94c5a3a12588d3132451 to your computer and use it in GitHub Desktop.
Save jpmhouston/94c5a3a12588d3132451 to your computer and use it in GitHub Desktop.
@implementation NSDictionary (MapDictKeysContainingPeriods)
- (NSDictionary *)dictionaryWithPeriodsInKeysMappedTo:(NSString *)replacement
{
NSMutableDictionary *updatedDictionary = [self mutableCopy];
NSAssert1(updatedDictionary != self, @"mutableCopy returned same object pointer: %@", updatedDictionary); // i don't think this ever happens
BOOL changed = NO;
for (NSString *key in updatedDictionary.allKeys)
{
id value = [updatedDictionary objectForKey:key];
id newValue = value;
if ([value isKindOfClass:[NSArray class]])
{
newValue = [value arrayWithPeriodsInDictionaryKeysMappedTo:replacement];
}
else if ([value isKindOfClass:[NSDictionary class]])
{
newValue = [value dictionaryWithPeriodsInKeysMappedTo:replacement];
}
NSMutableString *updatedKey = [key mutableCopy];
if ([updatedKey replaceOccurrencesOfString:@"." withString:replacement options:0 range:NSMakeRange(0, key.length)] > 0)
{
[updatedDictionary removeObjectForKey:key];
[updatedDictionary setObject:newValue forKey:updatedKey];
changed = YES;
}
else if (newValue != value)
{
[updatedDictionary setObject:newValue forKey:key];
changed = YES;
}
}
return changed ? updatedDictionary : self;
}
@end
@implementation NSArray (MapDictKeysContainingPeriods)
- (NSArray *)arrayWithPeriodsInDictionaryKeysMappedTo:(NSString *)replacement
{
NSMutableArray *updatedArray = [self mutableCopy];
NSAssert1(updatedArray != self, @"mutableCopy returned same object pointer: %@", updatedArray); // i don't think this ever happens
BOOL changed = NO;
NSUInteger index = 0;
for (id element in updatedArray)
{
id newElement = element;
if ([element isKindOfClass:[NSArray class]])
{
newElement = [element arrayWithPeriodsInDictionaryKeysMappedTo:replacement];
}
else if ([element isKindOfClass:[NSDictionary class]])
{
newElement = [element dictionaryWithPeriodsInKeysMappedTo:replacement];
}
if (newElement != element)
{
[updatedArray replaceObjectAtIndex:index withObject:newElement];
changed = YES;
}
++index;
}
return changed ? updatedArray : self;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment