Objective-C: How to create a dictionary?
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. For more information, refer to NSDictionary class.
Let’s create an empty dictionary using NSDictionary
class in Objective-C,
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
// Empty dictionary stored in dict
NSDictionary *dict = [NSDictionary dictionary];
NSLog(@"value of dict is %@",dict);
return 0;
}
outputvalue of dict is {}
In the above code, an empty dictionary initialised, and it is stored in dict
.
Let’s create a new dictionary using NSDictionary
class in Objective-C,
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys: @"value", @"key", nil];
NSLog(@"value of dict is %@",dict);
return 0;
}
outputvalue of dict is {key = value; }
In the above code, a dictionary initialised with key as key
and value value
, and it is stored in dict
.
I hope my article helps you understand how to create a dictionary in Objective-C.
If you like my articles, please follow me. You can also support me by buying me a coffee.