简体   繁体   English

获取核心数据SQLite数据库的数量

[英]Getting Number of out Core-Data SQLite Database

Using Core-Data to hold various information, one of which is a 'number' attribute (Int(16)). 使用核心数据保存各种信息,其中之一是“数字”属性(Int(16))。 I try to take it out of the database using: number = (int)[info valueForKey:@"number"] ; 我尝试使用以下方法将其从数据库中取出: number = (int)[info valueForKey:@"number"] ;

Unfortunately, this always gives some awful result, like 2895891275 when it should be returning 3. 不幸的是,这总是会产生一些可怕的结果,例如2895891275应该返回3。

Would appreciate any help, thanks! 希望得到任何帮助,谢谢!

valueForKey returns an object, not an int. valueForKey返回一个对象,而不是一个int。 The fact that you're having to cast it explicitly should be a warning sign. 您必须显式转换它的事实应该是一个警告信号。 Try: 尝试:

number = [[info valueForKey:@"number"] intValue];

To expand on @duskwuffs answer: 要扩展@duskwuffs答案:

All values in Core Data are objects. 核心数据中的所有值都是对象。 When you set an attribute type to, say, Int16, Core Data will create an NSNumber object. 当您将属性类型设置为Int16时,Core Data将创建一个NSNumber对象。

This code: 这段代码:

number = (int)[info valueForKey:@"number"]

... gives you a huge number because [info valueForKey:@"number"] returns an instance of NSNumber, an object, which you cast to an int. ...给您一个巨大的数字,因为[info valueForKey:@"number"]返回一个NSNumber的实例,该对象已转换为int。 When you cast an object to an int you actually cast it's address in memory to an int and so end up with a large nonsensical number. 当您将一个对象强制转换为一个int时,实际上是将其在内存中的地址强制转换为一个int,因此最终得到一个很大的无意义的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM