Getting Number of out Core-Data SQLite Database
Using Core-Data to hold various information, one of which is a 'number' attribute (Int(16)). I t开发者_如何学运维ry 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!
valueForKey
returns an object, not an 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:
All values in Core Data are objects. When you set an attribute type to, say, Int16, Core Data will create an NSNumber object.
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. 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.
精彩评论