Skip to content

Instantly share code, notes, and snippets.

@Abizern
Created September 10, 2013 10:55
Show Gist options
  • Save Abizern/6507819 to your computer and use it in GitHub Desktop.
Save Abizern/6507819 to your computer and use it in GitHub Desktop.
A category method that replaces the keys in the receiver with the new key provided in the keyMapping
//
// NSDictionary+JCSKeyMapping.h
//
// Created by Abizer Nasir on 06/08/2013.
// Copyright (c) 2013 TicketingHub. All rights reserved.
//
@import Foundation;
@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.
// Copyright (c) 2013 TicketingHub. All rights reserved.
//
#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