做了一些額外的研究。我發現下面的鏈接: 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