struct myStruct {
NSUInteger value;
NSString *s;
} myItem[2] = {
{ 1, @"test"},
{ 2, @"test2"}
};
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSValue valueWithPointer:&myItem[0]], @"myKey1",
[NSValue valueWithPointer:&myItem[1]], @"myKey2",
nil];
Tuesday, February 2, 2010
How to Use Struct in NSDictionary
Thought I wanted to use a NSDictionary for some reason, but after all the trouble didn't. However it was quite a challenge to make it work, so I'll post here a code sample. Maybe it will be useful at some other time:
Subscribe to:
Post Comments (Atom)
Well, this stores a pointer, not the value of the struct itself. If the struct goes out of scope, you will have a dangling pointer
ReplyDeleteHmm, now that I look at it - you are absolutely right! Happy I didn't use the code after all :) Code seems to rely on having NSArray myItem and NSDictionary myDict within same object, which would (should) make sure both exist at the same time. However myDict depends on myArray and will fail, if myArray would happen to disappear. You can change NSInteger value freely, but NSString *s does look a bit suspicious. More investigation is needed, proceed with caution.
ReplyDelete