做了一些额外的研究。我发现下面的链接: How to implement the new Core Data model builder 'unique' property in iOS 9.0 Beta
1)我加了一个mergePolicy我managedObjectContext定义,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”作为唯一的密钥或“约束”到我的项目CoreData实体,CoreData允许我执行UPSERT。 UP日期记录密钥是否存在或在SERT记录密钥是否不存在。此链接还显示如何为CoreData实体设置唯一约束。
Core Data Framework Reference -> NSMergePolicy Class Reference