从表视图选择快速使用CoreData

时间:2019-07-11 22:06:17

标签: swift core-data save

我有2个函数,一个应将字符串保存到CoreData属性,而另一个要获取它。这是通过从项目中其他地方复制工作代码来编写的,所以我不知道为什么当我打印'currentSetting'的内容时会显示为nil。

从didSelectRowAtIndexPath调用save函数,并将其作为参数发送到indexPath.row中,这将从数组中获取一个String。

func getImageSetting() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Settings")
    do {
        let fetcher = try context.fetch(fetchRequest)
        let data = fetcher as? [NSManagedObject]
        if let results = data {
                let settingResult = results[0]
                currentSetting = settingResult.value(forKey: "imageQuality") as? String
                print(currentSetting as Any)
            } else { print ("error") }
        }
        catch let error as NSError {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
}

func saveSetting(selection: Int) {
    let coreSelection = choices[selection]
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext
    let itemEntity = NSEntityDescription.entity(forEntityName: "Settings", in: managedContext)!
    let item = NSManagedObject(entity: itemEntity, insertInto: managedContext)
    item.setValue(coreSelection, forKey: "imageQuality")
    do {
        try managedContext.save()
    } catch let error as NSError {
        fatalError("Unresolved error \(error), \(error.userInfo)")
    }
}

0 个答案:

没有答案