ios - 为什么我得到 "Swift Dynamic Cast Failed"? :/

标签 ios xcode swift

我想知道是否有人可以向我解释有关编程的“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/

相关文章:

iphone - 显示 CGRect 位置重置我的图像位置

ios - 在展开可选值时,将可选字符串分配给 UITableView 中的 UILabel 以意外发现 nil 结束

ios - 应用程序运行一段时间后出现错误 3840 "JSON text did not start with array or object and option to allow fragments not set."

ios - 在应用程序内登录 iCloud

ios - 如何允许用户每 "n"秒刷新一次表?

ios - 如何在 Codemagic 中指定目标平台 ios 版本号

ios - ${PRODUCT_NAME} 未定义错误

iphone - 在 Xcode 中向我的 Storyboard添加标签

ios - 禁用 iMessage 应用调整大小

IOS Swift Segue 使用来自选定单元格而不是支持数组的数据