xcode 无法将“__NSCFNumber”()类型的值快速转换为“NSArray”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30824506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Could not cast value of type '__NSCFNumber' () to 'NSArray' swift
提问by Farhad
Why can't cast NSCFNumber (Core Data) to NSArray?
为什么不能将 NSCFNumber (Core Data) 转换为 NSArray?
Error:
错误:
Could not cast value of type '__NSCFNumber' (XXXXXXXX) to 'NSArray' (XXXXXXXX).
无法将“__NSCFNumber”(XXXXXXXX)类型的值转换为“NSArray”(XXXXXXXX)。
Code:
代码:
//Fetch Settings
func fetchAccounSetting(){
let entityDescription = NSEntityDescription.entityForName("UserSettings", inManagedObjectContext: Context!)
let request = NSFetchRequest()
//let data = UserSettings(entity: entityDescription!, insertIntoManagedObjectContext: Context)
request.entity = entityDescription
var dataObjects: [AnyObject]?
do {
dataObjects = try Context?.executeFetchRequest(request)
} catch let error as NSError {
print(error)
dataObjects = nil
}
for result in dataObjects as! [NSManagedObject] {
let dataSelected = NSArray(array: result.valueForKey("favCategory")! as! NSArray)
print(dataSelected)
}
UPDATE:How can I receive the Count of dataSelected
?
更新:我怎样才能收到计数dataSelected
?
采纳答案by Kelvin Lau
Core Data isn't capable of storing arrays or dictionaries in the first place. I remember encountering this problem before as I was learning.
Core Data 一开始就不能存储数组或字典。我记得我之前在学习时遇到过这个问题。
AKA, your dataObjects
array doesn't have anything that can be typecasted into an NSArray
. The way to do this is to model a to-many relationship (which creates a Set
), which can imitate an array.
又名,您的dataObjects
数组没有任何可以类型转换为NSArray
. 这样做的方法是对一对多关系建模(创建一个Set
),它可以模仿一个数组。
回答by Aaron Brager
result.valueForKey("favCategory")!
is returning a number, but it looks like you're expecting an array.
result.valueForKey("favCategory")!
正在返回一个数字,但看起来您正在等待一个数组。
Perhaps you meant:
也许你的意思是:
let dataSelected = [result.valueForKey("favCategory")!]
If you know the type you're getting back you can optionally cast it:
如果您知道要返回的类型,则可以选择强制转换它:
let dataSelected = [result.valueForKey("favCategory")!]
if let dataSelected = dataSelected as? [NSNumber] {
// dataSelected is of type [NSNumber] a.k.a. Array<NSNumber>
print(dataSelected)
}