Wednesday, June 19, 2013

NSMutableDictionary dictionaryWithCapacity example in Objective C (iOS).

NSMutableDictionary dictionaryWithCapacity

Creates and returns a mutable dictionary, initially giving it enough allocated memory to hold a given number of entries.

+ (id)dictionaryWithCapacity:(NSUInteger)numItems

The initial capacity of the new dictionary.

Return Value
A new mutable dictionary with enough allocated memory to hold numItems entries.

Discussion of [NSMutableDictionary dictionaryWithCapacity]
Mutable dictionaries allocate additional memory as needed, so numItems simply establishes the object’s initial capacity.

NSMutableDictionary dictionaryWithCapacity example.
To set an array as a key for another array as an object. You can do this with the following appraoch.

NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithCapacity:1];

NSArray *valueArray = [NSArray arrayWithObjects:@"v1", @"v2", nil];
NSArray *keyArray = [NSArray arrayWithObjects:@"k1",@"k2", nil];

[myDictionary setObject:valueArray forKey:keyArray];
NSLog(@"myDictionary: %@", myDictionary);

Example of [NSMutableDictionary dictionaryWithCapacity].
NSMutableDictionary *settings= [NSMutableDictionary dictionaryWithCapacity:10];
[settings setObject:@"2400" forKey:@"test"];

NSMutableDictionary dictionaryWithCapacity example.
self.venues = [NSArray arrayWithObjects:@"GSC One Utama",@"GSC Midvalley",@"TGV KLCC", @"TGV Sunway Pyramid", nil];

NSDictionary *venueDict = [NSDictionary dictionaryWithObject:self.venues forKey:@"venue:"];

NSMutableDictionary *mutableVenueDict = [NSMutableDictionary dictionaryWithCapacity:10];
[mutableVenueDict setObject:self.venues forKey:@"venue:"];

End of NSMutableDictionary dictionaryWithCapacity example article.