【问题标题】:Swift Array in CoreDataCoreData 中的 Swift 数组
【发布时间】:2016-12-18 11:37:34
【问题描述】:

我想将一个包含 28 个条目的数组存储到我的 coreData。有没有办法做到这一点? 我用这段代码试过了,但看起来这段代码只是重写了值。

let appDelegate =
        UIApplication.shared.delegate as! AppDelegate

    let managedContext = appDelegate.persistentContainer.viewContext

    let entity =  NSEntityDescription.entity(forEntityName: "PillTook",
                                             in:managedContext)

    let value = NSManagedObject(entity: entity!,
                                insertInto: managedContext)

    for var index in 0...27 {

        value.setValue(false, forKey: "took")

        do {
            try managedContext.save()

            pillTook.append(value)

        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    }

【问题讨论】:

    标签: arrays core-data swift3


    【解决方案1】:

    是的,您的代码仅创建一个NSManagedObject,并在for 循环中更新其took 属性的值。将 let value = ... 行移动到 for 循环中,为每次迭代创建一个新的 NSManagedObject。我还建议在 for 循环之后只保存一次上下文,而不是在每次迭代时保存:

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
    let managedContext = appDelegate.persistentContainer.viewContext
    
    let entity =  NSEntityDescription.entity(forEntityName: "PillTook", in:managedContext)
    
    for var index in 0...27 {
    
        let value = NSManagedObject(entity: entity!, insertInto: managedContext)
        value.setValue(false, forKey: "took")
        pillTook.append(value)
    }
    do {
        try managedContext.save()
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-09
      • 2019-12-01
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 2014-11-20
      • 1970-01-01
      相关资源
      最近更新 更多