2016-03-15 83 views
0

我正在尋找一種有效的方法來比較NSManagedObject數組和我從文件中讀取的基本相同的對象/結構數組,即文件「Item」具有與CoreData「Item」相同的屬性。這是場景。我有一套我從標籤分隔文件中讀取的項目。在遊戲的第一個版本中,我將這些項目存儲到名爲「Item」的核心數據實體中。將NSManagedObject數組與另一個「對象」類型的數組進行比較Swift 2

CoreData entity relationship

然後在比賽的第2版,我可以在平面文件中添加新的項目到平面文件或更新現有項目。我將在CoreData和文件數據之間使用的密鑰是itemId。當我發佈遊戲的版本2時,我將版本1的NSManagedObject項目數據讀取到數組中。我需要比較NSManagedObject數組和版本2文件項目數據。我可以遍歷文件數據併爲每個數組中的位置保留一個計數器,根據itemId匹配或不匹配將其遞增。如果匹配,我想用==來比較數據,因爲所有的屬性都是相同的,但是對象是不同的。我不想將文件數據對象存儲爲臨時或虛擬的NSManagedObject。如果我這樣做,那麼如果項目已經存在或者項目需要更新,那麼我需要刪除這個臨時對象。

我只處理100個項目,所以從性能角度來看也許沒有關係。創建NSManagedObjects用於比較目的並刪除它們似乎效率低下,反過來將NSManagedObject轉換爲「文件項」對象或結構似乎也是低效的。

所以,這個問題的簡短版本是,我如何有效地使用Swift 2比較NSManagedObject數組和另一個「Object」類型的數組?

回答

0

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

相關問題