Case-insensitive keys for NSDictionary

I am trying to use a case-sensitive case for JSON response to NSDictionary, because sometimes they change the type of response key, some the case of the camel, some the lowercase or other mixed combinations. Is there any built-in functionality for testing in case of sensitivity for this case?

Thanks.

+6
source share
4 answers

Recently, I have shared two classes that can satisfy your needs. They provide case-insensitive operations (called NSDictionary and NSMutableDictionary ), preserving the keys originally inserted.

Try:

https://github.com/keeshux/ios-components/tree/master/Components/Utils/KSCIDictionary

+6
source

The best way would be to set the key for NSDictionary, which will be either lowercase or uppercase,

For example, let's say I have an NSArray string. I could get keyName before using it and convert it using lowercaseString or uppercaseString

 NSString *itemName = @"lastName"; itemName = [itemName lowercaseString]; 

this will change the string to lastname, or if I use uppercaseString it will be LASTNAME

or you can also change the key name when adding to the dictionary as follows:

 NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject:objectToAdd forKey:[key uppercaseString]]; 
+5
source
 - (NSString *)lowercaseString 

This is the default NSString method, just use [key lowercaseString] when adding or reading from NSMutableDictionary.

+3
source

In my case, I do not need all the methods or properties of the dictionary. I just need case insensitive access. I created my own class (not the NSMutableDictionary superclass) and implemented methods to expand access to the window and made them case insensitive:

 - (id) objectForKeyedSubscript: (NSString *) key { NSMutableDictionary *theData = self->data; return theData[[key lowercaseString]]; } - (void) setObject: (id) newValue forKeyedSubscript: (NSString *) key { NSMutableDictionary *theData = self->data; theData[[key lowercaseString]] = newValue; } 

See also: http://clang.llvm.org/docs/ObjectiveCLiterals.html

0
source

Source: https://habr.com/ru/post/916510/


All Articles