Skip to content

Instantly share code, notes, and snippets.

@Abizern
Created August 6, 2013 11:58
Show Gist options
  • Select an option

  • Save Abizern/6163878 to your computer and use it in GitHub Desktop.

Select an option

Save Abizern/6163878 to your computer and use it in GitHub Desktop.
A category on NSDictionary that remaps the keys to new keys provided in the mapping, optionally removing null values.
//
// NSDictionary+JCSKeyMapping.h
//
// Created by Abizer Nasir on 06/08/2013.
//
#import <Foundation/Foundation.h>
@interface NSDictionary (JCSKeyMapping)
/*! A category method that replaces the keys in the receiver with the new key provided in the keyMapping
*
* If no mapping is provided for a key, the key is left unchanged.
* \param keymapping a dictionary which maps the existing key to the new key. If no mapping is provided for a key it is unchanged.
* \param removeNulls If YES, then if the value for a key in the receiver is [NSNull null], then it is not in the returned dictionary.
* \returns A new NSDictionary with the keys changed according to the mapping, on optionally with [NSNull null] values removed.
*/
- (NSDictionary *)jcsRemapKeysWithMapping:(NSDictionary *)keyMapping removingNullValues:(BOOL)removeNulls;
@end
//
// NSDictionary+JCSKeyMapping.m
//
// Created by Abizer Nasir on 06/08/2013.
//
#import "NSDictionary+JCSKeyMapping.h"
@implementation NSDictionary (JCSKeyMapping)
- (NSDictionary *)jcsRemapKeysWithMapping:(NSDictionary *)keyMapping removingNullValues:(BOOL)removeNulls {
__block NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (removeNulls) {
if ([obj isEqual:[NSNull null]]) return;
}
id newKey = keyMapping[key];
if (!newKey) {
[newDictionary setObject:obj forKey:key];
} else {
[newDictionary setObject:obj forKey:newKey];
}
}];
return [newDictionary copy];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment