【问题标题】:How to load basic initial and unique data to Core Data in Swift?如何在 Swift 中将基本的初始数据和唯一数据加载到 Core Data?
【发布时间】:2019-01-31 08:41:29
【问题描述】:

我正在处理一个项目,并希望将一些初始数据加载到 Core Data。核心数据中有两个属性。一是属于身体部位,二是属于它的属性。比如眼睛有四种颜色中的一种等等。数据如下:

眼睛是蓝色的

眼睛是棕色的

眼睛是绿色的

黑眼圈

发红

黑发

金发碧眼

衣服连衣裙

衣服裙子

衣服鞋子

衣服帽子

衣服手套

我搜索了一些 CSV 或 pList 版本,并听到了一些 sqLite 运输替代方案,但无法弄清楚如何有效地执行它们。

感谢任何清晰的解释,将小的初始数据加载到 Core Data 并从 Core Data 中删除任何重复值(如果存在)。提前谢谢你。

【问题讨论】:

  • 您要将初始数据保存在哪里?你想把它放在文件(plist、csv 等)还是你的代码中?
  • @DorianRoy 我希望将其保留在代码中,但任何解决方案都可能适合我

标签: swift core-data load unique


【解决方案1】:

这里有一些非常基本的代码来展示一种简单的方法。

您需要添加自己的标识符属性,以便检查项目是否已存在。假设您称其为id。 然后,当您启动您的应用程序时,您会检查每个默认值,如果它们不存在,请添加它们,如下所示:

// create a fetch request to get all items with id=1
let fr = NSFetchRequest<MyItem>(entityName: MyItem.entity().name!)
fr.predicate = NSPredicate(format: "id == %@", "1")
do {
    // if that request returns no results
    if (try myManagedObjectContext.fetch(fr).isEmpty == true) {
        // create the default item
        let item = NSEntityDescription.insertNewObject(forEntityName: MyItem.entity().name!, into: myManagedObjectContext) as! MyItem
        // set the id
        item.id = "1"
        // set other attributes here
    }
} catch {
    // fetching failed, handle the error
}

添加数据后,必须保存:

// save the context
do {
    try myManagedObjectContext.save()
} catch {
    // handle the error
}

您也可以使用 Core Datas Unique Constraints,但我认为这个解决方案要简单得多。希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多