Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray of NSDictionary - Simple Initialization syntax

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 ?

like image 482
Pierre de LESPINAY Avatar asked Feb 05 '13 16:02

Pierre de LESPINAY


People also ask

How do you declare NSArray in Objective-C?

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.

How do you set a value in NSDictionary?

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.

How do I create an NSDictionary in Objective-C?

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.

How do you convert NSDictionary to NSMutableDictionary?

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.


1 Answers

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

like image 89
peko Avatar answered Oct 03 '22 18:10

peko