objective-c 如何在 NSDictionary 中正确设置整数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1605224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:23:05  来源:igfitidea点击:

How to Properly set an integer value in NSDictionary?

objective-c

提问by Bill

The following code snippet:

以下代码片段:

NSLog(@"userInfo: The timer is %d", timerCounter);

NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:timerCounter] forKey:@"timerCounter"];

NSUInteger c = (NSUInteger)[dict objectForKey:@"timerCounter"];
NSLog(@"userInfo: Timer started on %d", c);

produces output along the lines of:

产生沿线的输出:

2009-10-22 00:36:55.927 TimerHacking[2457:20b] userInfo: The timer is 1
2009-10-22 00:36:55.928 TimerHacking[2457:20b] userInfo: Timer started on 5295968

(FWIW, timerCounter is a NSUInteger.)

(FWIW, timerCounter 是一个 NSUInteger。)

I'm sure I'm missing something fairly obvious, just not sure what it is.

我确定我遗漏了一些相当明显的东西,只是不确定它是什么。

回答by epatel

You should use intValuefrom the received object (an NSNumber), and not use a cast:

您应该intValue从接收到的对象 (an NSNumber) 中使用,而不是使用强制转换:

NSUInteger c = [[dict objectForKey:@"timerCounter"] intValue];

回答by Chuck

Dictionaries always store objects. NSInteger and NSUInteger are not objects. Your dictionary is storing an NSNumber (remember that [NSNumber numberWithInteger:timerCounter]?), which is an object. So as epatel said, you need to ask the NSNumber for its unsignedIntegerValueif you want an NSUInteger.

字典总是存储对象。NSInteger 和 NSUInteger 不是对象。您的字典正在存储一个 NSNumber(还记得[NSNumber numberWithInteger:timerCounter]吗?),它是一个对象。所以正如 epatel 所说,unsignedIntegerValue如果你想要一个 NSUInteger ,你需要向 NSNumber 询问它。

回答by Kez

Or like this with literals:

或者像这样使用文字:

NSUInteger c = ((NSNumber *)dict[@"timerCounter"]).unsignedIntegerValue;

You must cast as NSNumber first as object pulled from dictionary will be id_nullable and so won't respond to the value converting methods.

您必须首先转换为 NSNumber,因为从字典中提取的对象将是 id_nullable,因此不会响应值转换方法。