Created
September 15, 2014 19:13
-
-
Save jpmhouston/94c5a3a12588d3132451 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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