NSNumber 未正确转换并被解释为 NSCFString?
我正在迭代通过 API 调用而来的数字数组:
例如 [6000, 6001, 2000]
这是我的代码:
for(NSNumber* arrayID in array){
NSManagedObject *ent = [NSEntityDescription insertNewObjectForEntityForName:@"Genre" inManagedObjectContext:self.managedObjectContext];
[ent setValue:arrayID forKey:@"genreID"];
[ent setValue:name forKey:@"genreName"];
[mySet addObject:ent];
}
当设置 arrayID (这是我的核心数据中的 NSNumber)时,我遇到了崩溃
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "genreID"; desired type = NSNumber; given type = __NSCFString; value = 6002.'
:如果 arrayID 尚未转换为 NSNumber?当我输入时,Xcode 说它是一个 NSNumber,但如果我输入 [arrayID doubleValue],Xcode 会告诉我“无法为类型‘id’发送 doubleValue”
有什么想法吗?
I'm iterating through an array of numbers that come through an API call:
[6000, 6001, 2000] for example
Here's my code:
for(NSNumber* arrayID in array){
NSManagedObject *ent = [NSEntityDescription insertNewObjectForEntityForName:@"Genre" inManagedObjectContext:self.managedObjectContext];
[ent setValue:arrayID forKey:@"genreID"];
[ent setValue:name forKey:@"genreName"];
[mySet addObject:ent];
}
When setting the arrayID (which is NSNumber in my core data), I get a crash:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "genreID"; desired type = NSNumber; given type = __NSCFString; value = 6002.'
It's as if arrayID has not been cast as an NSNumber? Xcode says its an NSNumber when I type it in, but if I put [arrayID doubleValue] for example, Xcode tells me that 'doubleValue cannot be sent for type 'id'
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅仅因为您将
arrayID
声明为NSNumber
指针,并不能保证arrayID
对象实际上是NSNumber
>。在这种情况下,数组似乎由NSString
组成。在 Objective-C 中,对象类型只是对编译器的真正提示,您可以将任何内容强制转换为任何内容,并调用对象上的任何方法,这些事情实际上只会在运行时失败。您必须查看
array
的创建位置才能了解实际类型。在这种情况下,如果它们实际上都是字符串,你可以这样做
Just because you declared
arrayID
as anNSNumber
pointer, it doesn't guarantee that thearrayID
object is actually anNSNumber
. In this case, the array appears to consist ofNSString
s.In Objective-C, the object types are only really hints to the compiler, you can cast anything to anything, and call any method on an object, these things only actually fail at runtime. You'll have to look at where
array
was created to see what the type actually is.In this case, if they are all in fact strings, you can do
你是如何创建你的数组的?听起来它确实包含 NSString,而不是 NSNumber。
How are you creating your array? It sounds like it really contains NSStrings, not NSNumbers.