xcode 为什么我会收到“Swift Dynamic Cast Failed”??:/
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25193646/
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
Why am I getting "Swift Dynamic Cast Failed" ?? :/
提问by Danai Ghirmay Fessahaie
I was wondering if someone could explain the concept of "cast" or "casting" to me regarding programming and also help me with the issue of getting "Swift dynamic cast failed" when trying to execute this code:
我想知道是否有人可以向我解释有关编程的“强制转换”或“强制转换”的概念,并帮助我解决在尝试执行此代码时出现“Swift 动态强制转换失败”的问题:
import UIKit
import CoreData
class vcMain: UIViewController {
@IBOutlet var txtUsername: UITextField!
@IBOutlet var txtPassword: UITextField!
@IBAction func btnSave(){
//println("Save button pressed \(txtUsername.text)")//Adds the text written, in the console
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObjectContext
newUser.setValue("Test Username", forKey: "username")
newUser.setValue("Test Password", forKey: "password")
context.save(nil)
println(newUser)
println("Object Saved.")
}
@IBAction func btnLoad(){
//println("Load button pressed \(txtPassword.text)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Im following a tutorial on youtube but cant figure out why its not working for me! Thanks in advance for any answers!
我正在关注 youtube 上的教程,但不知道为什么它对我不起作用!提前感谢您的任何答案!
回答by Hyman Lawrence
This line looks wrong:
这一行看起来不对:
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObjectContext
You're casting to a NSManagedObjectContext
when you probably meant to cast to a NSManagedObject
, so the line should be:
NSManagedObjectContext
当您可能打算转换为 a时,您正在转换为 a NSManagedObject
,因此该行应该是:
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
回答by Ethan
I agree with Hyman Lawrence's answer.
我同意Hyman劳伦斯的回答。
We are looking at the function NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context)
which, from the documentation, will return a objC type, id, which kinda translates to Swift as an AnyObject. This is to say the computer doesn't know what it is, but we do, because we read the documentation:
我们正在查看NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context)
文档中的函数,该函数将返回一个 objC 类型 id,它有点转换为 Swift 作为 AnyObject。这就是说计算机不知道它是什么,但我们知道,因为我们阅读了文档:
insertNewObjectForEntityForName:inManagedObjectContext: Creates, configures, and returns an instance of the class for the entity with a given name.
Return ValueA new, autoreleased, fully configured instance of the class for the entity named entityName. The instance has its entity description set and is inserted it into context.
insertNewObjectForEntityForName:inManagedObjectContext:为具有给定名称的实体创建、配置和返回类的实例。
返回值名为 entityName 的实体的类的新的、自动发布的、完全配置的实例。该实例具有其实体描述集并将其插入到上下文中。
Anyway, you can be safe to assume it is returning a type NSManagedObject, or some subclass of it.
无论如何,您可以安全地假设它正在返回一个类型 NSManagedObject 或它的某个子类。
Now about casting:
现在关于铸造:
Most of this is from the Swift iBook. So you already know that type casting / downcasting in swift is done by the asoperator. Because downcasting can fail, the type cast operator comes in two forms. 1) Forced asand 2) Optional as?
其中大部分来自 Swift iBook。所以你已经知道 swift 中的类型转换/向下转换是由as操作符完成的。因为向下转换可能会失败,所以类型转换运算符有两种形式。1) 强制为2) 可选为?
Basically the differnce is, use as?when you are not sure if the downcast will succeed, and use aswhen you are certain it will. Here is an example, where I have an array of type AnyObject called Vehicles..., which contains two different classes, Car and Truck, of which there are 5 cars and 2 trucks.
基本上区别在于,用作?当你不知道,如果低垂会成功,并且利用作为当你一定会的。这是一个示例,其中我有一个名为 Vehicles... 的 AnyObject 类型数组,其中包含两个不同的类 Car 和 Truck,其中有 5 辆汽车和 2 辆卡车。
var carCount = 0
var truckCount = 0
for vehicle in vehicles{
if let car = car as? Car
{
carCount++
} else
if let truck = truck as? Truck
{
truckCount++
}
}
At the end of this my counts are correct, and I have not thrown an error. But, trying to access any one of the elements of vehicles
, like vehicles[i] as Car
would be dangerous, because it might be a truck, and you are forcefully saying that it is a car. Runtime error!
最后,我的计数是正确的,我没有抛出错误。但是,尝试访问vehicles
, like 的任何一个元素vehicles[i] as Car
都是危险的,因为它可能是一辆卡车,而您强行说它是一辆汽车。运行时错误!
Anyway I hope that explains it a bit. If not, check out the chapter on type casting in the Swift iBook, page 391.
无论如何,我希望能解释一下。如果没有,请查看 Swift iBook 中有关类型转换的章节,第 391 页。
回答by user2294382
For anyone else out there with a similar problem. There is a little gotcha here.
对于其他有类似问题的人。这里有一个小问题。
If you are trying to generate a custom NSManagedObject subclass using the NSEntityDescription.insertNewObjectForEntityForName(Entity, inManagedObjectContext: context) method, then make sure that the swift class has the @objc() header added to the class. Otherwise you'll encounter a dynamic class cast failure also.
如果您尝试使用 NSEntityDescription.insertNewObjectForEntityForName(Entity, inManagedObjectContext: context) 方法生成自定义 NSManagedObject 子类,请确保 swift 类将 @objc() 标头添加到类中。否则,您还会遇到动态类转换失败。