Objective-C: How to create a mutable dictionary?

Akarsh Seggemu
2 min readJun 25, 2022

To store data in an unordered collection is possible using a dictionary. A dictionary in Objective-C forms an association between keys of same data type and values of data type.

Important to remember

  • A key is always unique, and it will not have any duplicates. As, it is used as an identifier to retrieve a value.
  • A value need not be unique, and it can be a duplicate. But its associated key is always unique.

In Objective-C, a dictionary is a NSDictionary class which is part of Collections inside Foundation framework. NSMutableDictionary is a subclass of NSDictionary. For more information, refer to NSMutableDictionary class.

NSDictionary object is immutable whereas, NSMutableDictionary is mutable.

Let’s create an empty dictionary using NSMutableDictionary class in Objective-C,

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
// Empty dictionary stored in dict
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSLog(@"value of dict is %@",dict);

return 0;
}

output
value of dict is {}

In the above code, an empty dictionary initialised, and it is stored in dict.

Let’s create a new dictionary using NSMutableDictionary class in Objective-C,

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
@"value", @"key", nil];
NSLog(@"value of dict is %@",dict);
[dict setObject: @"value two" forKey: @"key-two"];
NSLog(@"value of dict is %@",dict);
return 0;
}

output
value of dict is {key = value; }

value of dict is {key = value; "key-two" = "value two"; }

In the above code, a dictionary initialised with key as key and value value, and it is stored in dict. A new entry added to the dictionary dict with key as key-two and value as value two.

I hope my article helps you understand how to create a mutable dictionary in Objective-C.

If you like my articles, please follow me. You can also support me by buying me a coffee.

--

--

Akarsh Seggemu

IT Team Lead | MSc in Computer Science from Technische Universität Berlin | Writing articles to Empower Software Engineers and IT Leaders