当前位置: 动力学知识库 > 问答 > 编程问答 >

cocoa - Store int32_t in an NSDictionary

问题描述:

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?

网友答案:

+[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
分享给朋友:
您可能感兴趣的文章:
随机阅读: