在做了一些额外的研究之后。我找到了以下链接:
How to implement the new Core Data model builder 'unique' property in iOS 9.0 Beta
1) 我在 managedObjectContext 定义中添加了一个 mergePolicy,在注释后的第 4 行:
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return managedObjectContext
}()
2) 以及在插入对象后立即保存 managedObjectContext,我可以合并数据集。
if let contentLineArray = arrayFromContentsOfFileWithName("Item") {
// Loop through each item in the item file. Add each item and save.
// Using managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
for lineArray in contentLineArray {
// skip the header line
if lineArray == contentLineArray[0] {
continue
}
// get the individual attributes from the line
let lineAttributeArray = lineArray.componentsSeparatedByString("\t")
let itemEntity = NSEntityDescription.entityForName(kItem as String, inManagedObjectContext:managedObjectContext)
let fileItem = NSManagedObject(entity: itemEntity!, insertIntoManagedObjectContext: managedObjectContext) as! Item
// set the properties of the managed object from the file object
fileItem.itemId = Int(lineAttributeArray[0]) // unique key
fileItem.slot = lineAttributeArray[1]
fileItem.itemType = lineAttributeArray[2]
fileItem.itemName = lineAttributeArray[3]
fileItem.imageName = lineAttributeArray[4]
fileItem.level = Int(lineAttributeArray[5])!
fileItem.rarity = lineAttributeArray[6]
fileItem.strength = Int(lineAttributeArray[7])!
}
// conflicts are managed at the time of save
saveManagedContext()
// used for unit testing and validating
// let nameSpaceClassName = NSStringFromClass(Item)
// let className = nameSpaceClassName.componentsSeparatedByString(".").last! as String
// let sortItemId = NSSortDescriptor(key: "itemId", ascending: true, selector: "localizedStandardCompare:")
// let itemArray = CoreDataHelper.fetchEntities(className, managedObjectContext: managedObjectContext, predicate: nil, sortDescriptors: [sortItemId]) as! [Item]
// print(itemArray)
}
func saveManagedContext() {
if self.managedObjectContext.hasChanges {
do {
try self.managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
#if DEBUG
print("Managed context saved")
#endif
}
}
本质上,如果我将“itemId”作为唯一键或“约束”添加到我的 Item CoreData 实体,CoreData 允许我执行 UPSERT。如果键存在则UP记录记录,如果键不存在则SERT记录。此链接还显示了如何为 CoreData 实体设置唯一约束。
Core Data Framework Reference -> NSMergePolicy Class Reference