Showing posts with label NSValue. Show all posts
Showing posts with label NSValue. Show all posts

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.