Monday, December 5, 2011

What is an NSDictionary and NSMutableDictionary

This is how I define Dictionary data strcuture.

It's a table with following conditions.

  1. It has exactly 2 columns and n rows.
  2. Its first column title is "key" and second column title is "value"
  3. Column 1 (key) values are always "unique"

Objective-C Foundation framework provide us 2 kind of dictionaries. One which is mutable (virtually unlimited size) and editable values called NSMutableDictionary and the one which has a fixed size (set when initializing it) with non-editable values calledNSDictionary.

NSDictionary is normally used to hold dictionaries which we know for sure that we will only use them in our calculations but not adding new rows into it or editing its values e.g; we use it to hold dictionaries returned by some function.

NSMutableDictionary is used where we are not sure about the the total number of rows in our dataset e.g; when we are processing our json response and not sure in advance how many results will be there.

How to Use NSMutableDictionary

   // Creating an instance of NSMutableDictionary NSMutableDictionary *mutDictionary = [[NSMutableDictionary alloc] init];  // Adding Values in it. [mutDictionary setValue:@"1st" forKey:@"FirstKey"]; [mutDictionary setValue:@"2nd" forKey:@"SecondKey"];  // Getting values in dictionary NSLog(@"First Value %@",[mutDictionary valueForKey:@"FirstKey"]); NSLog(@"Second Value %@",[mutDictionary valueForKey:@"SecondKey"]);
How to Use NSDictionary
  // Creating an instance of NSDictionary NSDictionary *dictionary = [[NSDictionary alloc] init];  // Since NSDictionary size is fixed, we will not be able to add new rows in it [dictionary setValue:@"Value" forKey:@"Key"];   // will produce run time error  // So if you wanted to initialize NSDictionary with some data, you can do it with some // proper initializer like this NSDictionary *dictionary = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:@"ist",@"2nd",nil] forKeys:[NSArray arrayWithObjects:@"FirstKey", @"SecondKey", nil]];  // Getting values in dictionary NSLog(@"First Value %@",[dictionary valueForKey:@"FirstKey"]); NSLog(@"Second Value %@",[dictionary valueForKey:@"SecondKey"]);