如何在 Swift 中将基本的初始和唯一数据加载到 Core Data?
How to load basic initial and unique data to Core Data in Swift?
我正在做一个项目,希望将一些初始数据加载到 Core Data。核心数据中有两个属性。第一个属于正文部分,第二个属于它的 属性。比如眼睛有四种颜色之一等等。数据将如下所示:
蓝眼睛
棕色眼睛
绿色的眼睛
眼睛黑
头发红
黑发
金发
衣服连衣裙
衣服裙子
衣服鞋子
衣服帽子
衣服手套
我搜索了一些 CSV 或 pList 版本并听说了一些 sqlite 装运替代方案,但无法弄清楚如何有效地执行它们。
对于将小的初始数据加载到 Core Data 以及从 Core Data 中删除任何重复值(如果存在)的任何清晰解释,我表示感谢。提前谢谢你。
下面是一些非常基本的代码,展示了执行此操作的一种简单方法。
您需要添加自己的标识符属性,以便检查某个项目是否已存在。假设您称其为 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,但我认为这个解决方案要简单得多。希望这对您有所帮助!
我正在做一个项目,希望将一些初始数据加载到 Core Data。核心数据中有两个属性。第一个属于正文部分,第二个属于它的 属性。比如眼睛有四种颜色之一等等。数据将如下所示:
蓝眼睛
棕色眼睛
绿色的眼睛
眼睛黑
头发红
黑发
金发
衣服连衣裙
衣服裙子
衣服鞋子
衣服帽子
衣服手套
我搜索了一些 CSV 或 pList 版本并听说了一些 sqlite 装运替代方案,但无法弄清楚如何有效地执行它们。
对于将小的初始数据加载到 Core Data 以及从 Core Data 中删除任何重复值(如果存在)的任何清晰解释,我表示感谢。提前谢谢你。
下面是一些非常基本的代码,展示了执行此操作的一种简单方法。
您需要添加自己的标识符属性,以便检查某个项目是否已存在。假设您称其为 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,但我认为这个解决方案要简单得多。希望这对您有所帮助!