Swift:无法将“Int16”类型的值转换为预期的参数类型“AnyObject?” [复制]

2024-03-19

我收到以下错误:

无法将类型“Int16”的值转换为预期参数类型“AnyObject?”

在线上

person.setValue(Time, forKey: "Time")

当我运行这个应用程序时。函数的框架取自本教程 https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial并从String to Int16,以及实体和属性名称。

var people = [NSManagedObject]()

   func saveName(Time: Int16) {
    //1
    let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    //2
    let entity =  NSEntityDescription.entityForName("Person",
                                                    inManagedObjectContext:managedContext)

    let person = NSManagedObject(entity: entity!,
                                 insertIntoManagedObjectContext: managedContext)

    //3
    person.setValue(Time, forKey: "Time")

    //4
    do {
        try managedContext.save()
        //5
        people.append(person)
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
}

正如错误所说,Int16不是 Swift 中的对象,因此不能用于setValue(forKey:),它需要一个对象。尝试将其包裹在NSNumber,像这样:

person.setValue(NSNumber(short: Time), forKey: "Time")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift:无法将“Int16”类型的值转换为预期的参数类型“AnyObject?” [复制] 的相关文章

随机推荐