如何存储“int” NSMutableArray* 或 NSMutableDictionary* 中的值?以整数形式传入的 JSON 数据存在长期问题。
如何将 "int"
值存储在 NSMutableArray
或 NSMutableDictionary
中?以整数形式传入的 JSON 数据存在长期问题。
我应该尝试将这些整数存储为 NSNumber 对象还是仅存储为包含该整数的字符串?
如果我知道这些值将始终是自然数(数字>=0,包括零表示 null),那么对指针进行“原始”(int)转换有多危险。
我一直使用的整数是外键 ID来自数据库。
How do you store "int"
values in an NSMutableArray
or NSMutableDictionary
? Chronic problems with JSON data that come in as integers.
Should I try to store these integers as NSNumber
objects or just as strings that contain the integer?
How dangerous is it to do a "raw" (int) conversion on the pointers if I know the values will always be Natural Numbers (numbers>=0 including zero for null.)
The integers I'm always working with are Foreign Key Id's from a database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
像这样使用 NSNumber:
或者使用现代 Objective C 语法,您可以将以下内容用于表达式:
或者对于单独的数字:
Use NSNumber like this:
Or using modern Objective C syntax, you can use the following for expressions:
Or for lone numbers:
使用
NSNumber
对象(例如使用[NSNumber numberWithInt:value]
)Use
NSNumber
objects (e.g. using[NSNumber numberWithInt:value]
)正如其他人所说,您需要使用
NSNumber
,或者使用NSString
和数字的字符串表示形式。哪个并不重要,但NSNumber
会更有效。您不能只是传入一个
int
,让它被解释为指针,然后在退出时将其强制转换回来。原因是对象(int
将被解释为指向的指针)在添加到数组时将被发送retain
消息,这肯定会导致崩溃,因为它将是一个无效的指针。You need to use
NSNumber
, as others have said, or use anNSString
with the string representaton of the number. It really doesn't matter which, but theNSNumber
will be more efficient.You can't just throw in an
int
, let it be interpreted as a pointer, and then cast it back on the way out. The reason is that the object (that theint
will be interpreted as a pointer to) will be sent theretain
message when it is added to the array, and this will definately cause a crash since it will be an invalid pointer.您还可以使用:
You can also use:
您还可以像这样添加值
NSMutableArray *values = [NSMutableArray alloc]init];
[值 addObject:[NSNumber numberWithInt:23]];
You can also add value like this
NSMutableArray *values = [NSMutableArray alloc]init];
[values addObject:[NSNumber numberWithInt:23]];