Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutable Dictionary adding objects

Is there a more efficient way to add objects to an NSMutable Dictionary than simple iteration?

Example:

// Create the dictionary

NSMutableDictionary *myMutableDictionary = [NSMutableDictionary dictionary];    

// Add the entries

[myMutableDictionary setObject:@"Stack Overflow" forKey:@"http://stackoverflow.com"];
[myMutableDictionary setObject:@"SlashDotOrg" forKey:@"http://www.slashdot.org"];
[myMutableDictionary setObject:@"Oracle" forKey:@"http://www.oracle.com"];

Just curious, I'm sure that this is the way it has to be done.

like image 509
djt9000 Avatar asked Jul 12 '09 22:07

djt9000


People also ask

How do you add value in NSMutableDictionary?

You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).

How to define a dictionary in Objective-C?

Use shorthand syntax: @{@"key":@"value"} or @[@"item1"] and you can put them into #define.

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).

How do I create an 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.


3 Answers

NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:   [NSNumber numberWithDouble:acceleration.x], @"x",   [NSNumber numberWithDouble:acceleration.y], @"y",   [NSNumber numberWithDouble:acceleration.z], @"z",   [NSDate date], @"date",    nil]; 
like image 189
Andrew Johnson Avatar answered Sep 19 '22 15:09

Andrew Johnson


If you have all the objects and keys beforehand you can initialize it using NSDictionary's:

dictionaryWithObjects:forKeys:

Of course this will give you immutable dictionary not mutable. It depends on your usage which one you need, you can get a mutable copy from NSDictionary but it seems easier just to use your original code in that case:

NSDictionary * dic = [NSDictionary dictionaryWith....];
NSMutableDictionary * md = [dic mutableCopy];
... use md ...
[md release];
like image 21
stefanB Avatar answered Sep 22 '22 15:09

stefanB


Allow me to add some information to people that are starting.

It is possible to create a NSDictionary with a more friendly syntax with objective-c literals:

NSDictionary *dict = @{ 
    key1 : object1, 
    key2 : object2, 
    key3 : object3 };
like image 26
Tiago Almeida Avatar answered Sep 21 '22 15:09

Tiago Almeida