tags:

views:

511

answers:

5

Hi,

I want to Create a NSMutableDictionary with an Integer Mapping to an strucuter(struct). Example:

int nVar = 1;
typedef struct 
{
  NSString *pstrName;
}sSampleStruct;
sSampleStruct *sObject = {@"test"};
NSMutableDictioary *pSampleMap = [[NSMutableDictioary allo] init];
[pSampleMap setObject:sObject forKey:[[nsnumber alloc] initwithint:nVar];

This is wat i want to do? But as struct is not an object its throwing a warning? Is thr any way i can create a dictionary with strutures. Or is thr any other way to create a map with structure?

Kindly reply soon.....

Thank you Pradeep.

+2  A: 

Take a look at NSValue:

[pSampleMap setObject:[NSValue value:&sObject withObjCType:@encode(sSampleStruct)] forKey:[NSNumber numberWithInt:nInt]];

Also, you're having a memory leak in [[NSNumber alloc] initWithInt:nVar] and you're code will not even complile since Objective-C is case-sensitive.

JoostK
Hey thanks.....tat was really a quick reply...It works.The sample i wrote was just to make my requirement clear.Thanks for pointing to the memory leak.
Pradeep Kumar
+1  A: 

You are right in that both the key and value in a NSDictionary must be objects. What you're looking for is NSValue.

From the docs:

An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids. The purpose of this class is to allow items of such data types to be added to collections such as instances of NSArray and NSSet, which require their elements to be objects. NSValue objects are always immutable.

Something like (with a slight cleanup of the code):

typedef struct 
{
    NSString *pstrName;
} sSampleStruct;

// Changed sObject to non-pointer so it can be initialized with a literal
sSampleStruct sObject = {@"test"};

// Corrected spelling of NSMutableDictionary
NSMutableDictionary *pSampleMap = [[NSMutableDictionary alloc] init];

// Changed to [NSNumber numberWithInt:] to avoid leaking memory
// Corrected spelling and capitalization of NSNumber
[pSampleMap setObject:[NSValue valueWithPointer:&sObject] 
               forKey:[NSNumber numberWithInt:nVar]];
Jarret Hardie
Hey im pretty impressed with the way you answered it...Thanks a lot....I would be needing a lot of help...as i need to finish of a tool.by end of this week..hope this forum helps me out.
Pradeep Kumar