我想知道是否有人可以向我解释有关编程的“cast”或“casting”的概念,并帮助我解决在尝试执行此代码时出现“Swift dynamic cast failed”的问题:
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.
}
}
我正在关注 YouTube 上的教程,但无法弄清楚为什么它对我不起作用!
最佳答案
这一行看起来不对:
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObjectContext
当您可能打算转换为 NSManagedObject
时,您正在转换为 NSManagedObjectContext
,因此该行应为:
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
关于ios - 为什么我得到 "Swift Dynamic Cast Failed"? :/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193646/