views:

184

answers:

3

Hi,

How can I store a variable of type int32_t (e.g. for ABPropertyID) in an NSDictionary?

[NSNumber numberWithInt:...] doesn't seem to work.

Thanks


From the comments:

NSLog(@" %@ %@ ", [NSNumber numberWithLong:kABPersonFirstNameProperty], kABPersonFirstNameProperty);

Prints: 0 (null) Any ideas?

+1  A: 

+[NSNumber numberWithInteger:] will hold a 32-bit number nicely on all 32-bit and 64-bit systems. +[NSNumber integerValue] will retrieve it. If you need it unsigned you can use `+[NSNumber numberWithUnsignedInteger:].

TechZen
While what you say is true, I think in this context it's quite misleading, because: A) the same is true for the `numberWithInt:` method used in the question (holding a 32-bit number nicely on all 32-bit and 64-bit systems), and B) @Dave's problem is obviously elsewhere.
Nikolai Ruhe
`numberWithInt:` will produce a negative number for some 32-bit values while `numberWithInteger:' will not. I thought that was his problem because I answered before he fleshed his question out.
TechZen
+1  A: 

As everyone else has said, NSNumber will work for this. However, there are two other options you should be at least vaguely aware of: CFDictionary (the same thing as NSDictionary under the hood, but it lets you store arbitrary pointers or pointer-sized integers) and NSMapTable.

Ahruman
+1  A: 

In this case, using NSNumber seems like the best idea.

For harder cases, you can always use NSValue or NSData to put any type or pointer into a Objective-C object that can be stored in Cocoa collections.

int32_t myInt = 42;
NSValue *myValue = [NSValue value:&myInt withObjCType:@encode(int32_t)];
Adrian