I'm beginning Objective-C (coming from Python)
I need to create and initialize a simple dictionary.
In Python I was used to do:
arr = [
{'fieldX': value1, 'fieldY': value2},
{'fieldX': value3, 'fieldY': value3},
]
Here is what I'm doing in Objective-C
NSArray *arr = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
value1, @"fieldX", value2, @"fieldY"
, nil]
, [NSDictionary dictionaryWithObjectsAndKeys:
value3, @"fieldX", value4, @"fieldY"
, nil]
, nil
];
Isn't there a simpler way to initialize this array of dictionaries ?
Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.
You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.
Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.
Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.
since ios6 you can use literals
NSArray *arr = @[
@{@"fieldX": value1, @"fieldY": value2},
@{@"fieldX": value3, @"fieldY": value3}
];
more info: http://clang.llvm.org/docs/ObjectiveCLiterals.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With