开发者

Store int32_t in an NSDictionary

开发者 https://www.devze.com 2022-12-17 23:42 出处:网络
How can I store开发者_如何学JAVA a variable of type int32_t (e.g. for ABPropertyID) in an NSDictionary?

How can I store开发者_如何学JAVA 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?


+[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:]`.


I assume here that Dave's issue is specific to the kAB... constants--I may be mistaken in which case ignore the following :)

I believe that the issue here is not that you are using incorrect syntax; it's an order-of-initialization problem. I'm guessing that you are attempting this operation before having initialized the kAB... constants -- e.g., by calling ABAddressBookCreate(). Somewhat confusing the issue is the snippet:

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

which should be:

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

Here's my output -- prior to calling ABAddressBookCreate():

NSLog(@"Check: %d %d %d", kABPersonFirstNameProperty,kABPersonMiddleNameProperty,kABPersonLastNameProperty);

produces

Check: 0 0 0

after the call, the same log statement produces

Check: 0 6 1


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.


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)];
  • Number and Value Programming Topics for Cocoa: Using Values
  • NSValue Class Reference
0

精彩评论

暂无评论...
验证码 换一张
取 消