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.
You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).
Use shorthand syntax: @{@"key":@"value"} or @[@"item1"] and you can put them into #define.
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).
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.
NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithDouble:acceleration.x], @"x", [NSNumber numberWithDouble:acceleration.y], @"y", [NSNumber numberWithDouble:acceleration.z], @"z", [NSDate date], @"date", nil];
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];
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 };
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