Swift,CoreData没有插入记录

时间:2017-08-18 09:23:25

标签: swift core-data

我有一个错误,其中标记错误//错误

db为空,我尝试附加Persistence记录,然后设置其值

tasks[0].persistencevalue = "Some Text"

任何帮助都将不胜感激。

由于

堆栈显示:

  

2017-08-18 10:09:07.158047 + 0100 Ontrack [6491:1684506] [错误]错误:   CoreData:错误:无法调用指定的初始化程序   NSManagedObject类'持久'       CoreData:错误:CoreData:错误:无法在NSManagedObject类上调用指定的初始化程序“Persistence”2017-08-18 10:09:08.678 Ontrack [6491:1684506] - [Persistence setPersistencevalue:]:无法识别的选择器发送到实例   0x60800026a040       2017-08-18 10:09:08.681 Ontrack [6491:1684506] ***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:   ' - [Persistence setPersistencevalue:]:发送到的无法识别的选择器   实例0x60800026a040'

func Update() {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let app = (UIApplication.shared.delegate as! AppDelegate )        

    var tasks: [ Persistence] = []    

    let pers = Persistence()

    tasks.append(pers)
    cnt = tasks.count
    // ERRORS HERE 
    tasks[0].persistencevalue = Rate.text!
    // END ERROR
}

1 个答案:

答案 0 :(得分:0)

感谢您的帮助,我能够使用以下代码解决问题。希望它可以帮助有同样问题的人。

func Update() {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let app = (UIApplication.shared.delegate as! AppDelegate )

    var persistencies: [ Persistence]?


    var cnt = persistencies?.count

    var perRec: AnyObject! = NSEntityDescription.insertNewObject(forEntityName: "Persistence", into: context) as NSManagedObject

    perRec.setValue(DbKeys.PERSISTENCE_SPEECHRATE_KEY, forKey: "persistencekey")
    perRec.setValue(Rate.text, forKey: "persistencevalue")

    do {
     try context.save()
    } catch {
        print (" ERROR")
    }

    app.saveContext()

    do {
        persistencies = try context.fetch(Persistence.fetchRequest())
    } catch {
        print("Fetching Failed")
    }


    cnt = persistencies?.count

  }