Friday, February 4, 2011

Saving custom structure in NSMutableDictionary/NSMutableArray with iPhone SDK

Recently while working on iPhone code, I required to store my custom structure in to NSMutableDictionary.

Well, NSMutableDictioary only store object derived from NSObject, so either we can make our structure, a class which is derived from NSObject and that's quite heavy and inefficient solution.

Better solution is to store custom structure in NSValue object and save NSValue to NSMutableDictionary.

As apple document suggest, The purpose of NSValue is to allow items of int, float, and char, pointers, structures and object ids data types to be added to collection objects such as instances of NSArray or NSSet, which require their elements to be objects.

Following is simple code that show how custom structure can be store in NSMutableDictionary.
Creating instance of NSMutableDictionary

NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithCapacity:1];

Code to save structure in NSMutableDictionary.

MyStruct myStruct;
myStruct.someInt = 100; myStruct.someBool = NO;
NSValue* valueForStruct = [NSValue valueWithBytes:&myStruct objCType:@encode(MyStruct)];
[map setObject:valueForStruct forKey:@"MyStruct"];

Code to retrieve structure from NSMutableDictionary.

NSValue* valueForStruct = [map objectForKey:@"MyStruct"];
MyStruct myStruct;
[valueForStruct getValue:&myStruct];
NSLog(@"int val:%i, bool val:%i",myStruct.someInt, myStruct.someBool);

Though, it's not that difficult i thought to share this, hope it will help.


  1. Thank you very much

  2. 1. [map setObject:valueForStruct forKey:@"MyStruct"];
    2. NSValue* valueForStruct = [map objectForKey:@"MyStruct"];

    In my opinion using @"MyStruct" in the above two cases creates confusion for someone reading this code for the first time because MyStruct is also the name of the struct datatype. An improvement on the code would be to use "zero" or "first" or any other key string.

    Thanks for publishing this code.

  3. I was looking around so much and i found this! Thanks a lot.