Is there a literal syntax for mutable collections?
Objective CCocoaNsmutablearrayNsmutabledictionaryObjective C-LiteralsObjective C Problem Overview
I know I can create an NSArray
with @[@"foo", @"bar"]
or an NSDictionary
with @{@0 : @"foo", @1 : @"bar"}
.
Is there a literal syntax for creating an NSMutableArray
or an NSMutableDictionary
?
Objective C Solutions
Solution 1 - Objective C
There isn't a built in way, but I just usually use mutableCopy
like this:
NSMutableArray *array = [@[ @"1", @"2", @"3" ] mutableCopy];
Solution 2 - Objective C
No. Just as how there isn't a syntax for creating an NSMutableString
either. Mutable objects are not particularly suited to literal values.
Solution 3 - Objective C
> But, is there a literal syntax for creating an NSMutableArray or an NSMutableDictionary?
No. Best alternative:
[@[ @"foo", @"bar"] mutableCopy]
Solution 4 - Objective C
Yes. But not quite. Take a look at this;
NSMutableArray *list = [@[] mutableCopy];
This creates a non-mutable array @[]
and calls mutableCopy
which returns a NSMutableArray *
. In place of @[]
, you can give any array literal.
Solution 5 - Objective C
If you have a nested literal of arrays and dictionaries, you can turn this into a fully mutable version by going through NSJSONSerialization
. For example:
NSArray* array = @[ @{ @"call" : @{ @"devices" : @[ @"$(devices)" ] } } ];
NSData* data = [NSJSONSerialization dataWithJSONObject:array
options:0
error:nil];
NSJSONReadingOptions options = NSJSONReadingMutableContainers |
NSJSONReadingMutableLeaves;
NSMutableArray* mutableArray = [NSJSONSerialization JSONObjectWithData:data
options:options
error:nil];
It's a bit of a detour, but at least you don't have to write out the code yourself. And the good thing is that NSJSONSerialization
is very fast.