0

Using Core-Data to hold various information, one of which is a 'number' attribute (Int(16)). I try to take it out of the database using: number = (int)[info valueForKey:@"number"];

Unfortunately, this always gives some awful result, like 2895891275 when it should be returning 3.

Would appreciate any help, thanks!

4

2 回答 2

7

valueForKey返回一个对象,而不是一个 int。您必须显式转换它的事实应该是一个警告信号。尝试:

number = [[info valueForKey:@"number"] intValue];
于 2011-06-22T23:29:30.847 回答
1

要扩展@duskwuffs 答案:

Core Data 中的所有值都是对象。当你将一个属性类型设置为 Int16 时,Core Data 将创建一个 NSNumber 对象。

这段代码:

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

... 给你一个巨大的数字,因为[info valueForKey:@"number"]返回一个 NSNumber 的实例,一个对象,你将它转换为一个 int。当您将对象转换为 int 时,您实际上将其在内存中的地址转换为 int,因此最终会得到一个很大的无意义数字。

于 2011-06-23T14:14:12.203 回答