English 中文(简体)
Storing ints in a Dictionary
原标题:

As I understand, in Objective-C you can only put Objects into dictionaries. So if I was to create a dictionary, it would have to have all objects. This means I need to put my ints in as NSNumber, right?

SOo...

NSNumber *testNum = [NSNumber numberWithInt:varMoney];


NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:@"OMG, Object 1!!!!" forKey:@"1"];
[dictionary setObject:@"Number two!" forKey:@"2"];
[dictionary setObject:testNum forKey:@"3"];


NSNumber *retrieved = [dictionary objectForKey:@"3"];
int newVarMoney = [retrieved intValue];

Where varMoney is an int that has been declared earlier. My question is, is there a better way to store "int" in a dictionary than putting it into a NSNumber?

Thanks!

Edit: 04/25/13

It s been a long time since I asked this question. For people stumbling on it in the future, there are easier ways to do this with the Apple LLVM Compiler 4.0, which has been default in Xcode for a bit. (ARC)

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:@1337 forKey:@"1"];

That s it, use the @1337 Syntax to quickly create NSNumber objects. Works with Variables, so my above could become:

[dictionary setObject:@(varMoney) forKey:@"3"];

or

dictionary[@"mykey"] = @1337;

Simpler.

最佳回答

You are correct, NSNumber is the normal way to handle this situation. You can use NSValue or NSDecimalNumber, too.

问题回答

If you are prepared to fall back to using Core Foundation (CFDictionaries) you can store anything you like. I ve definitely made dictionaries into which I put arbitrary void* values.

You need to do a little more plumbing but not much, and its all documented.

Sorry but no :( Not as far as I know. Reason being that integers aren t objects, and NSDictionary only stores objects.





相关问题
Code sign Error

I have created a new iPhone application.I have two mach machines. I have created the certificate for running application in iPhone in one mac. Can I use the other mac for running the application in ...

ABPersonViewController Usage for displaying contact

Created a View based Project and added a contact to the AddressBook using ABAddressBookRef,ABRecordRef now i wanted to display the added contact ABPersonViewController is the method but how to use in ...

将音频Clips从Peter改为服务器

我不禁要问,那里是否有任何实例表明从Peit向服务器发送音响。 I m不关心电话或SIP风格的解决办法,只是一个简单的袖珍流程......

• 如何将搜查线重新定位?

我正试图把图像放在搜索条左边。 但是,问题始于这里,搜索条线不能重新布署。

热门标签