簡體   English   中英

iOS - 數據一旦存入Core Data

[英]iOS - Data persist once into Core Data

我正在嘗試將大量數據保存到核心數據中。 我可以設法將所有數據保存到核心數據中,但在核心數據中包含重復數據是沒有意義的,因為該函數將在每個項目構建時執行一次。 在我添加新記錄之前,我現在想的方法是清空實體的記錄。 只是想知道是否有另一種方法來確保數據只持續一次?

func persistCurrencyData() {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let currencyEntity = NSEntityDescription.entityForName("Currency", inManagedObjectContext: managedContext)


    let countryEntity = NSEntityDescription.entityForName("Country", inManagedObjectContext: managedContext)

    for currency in currencies {
      let currencyObject = CurrencyCore(entity: currencyEntity!, insertIntoManagedObjectContext: managedContext)

      currencyObject.setValue(currency.code, forKeyPath: "code")
      currencyObject.setValue(currency.name, forKeyPath: "name")

      for country in currency.country! {
        let countryObject = CountryCore(entity: countryEntity!, insertIntoManagedObjectContext: managedContext)

        countryObject.setValue(country.name, forKeyPath: "name")
        countryObject.setValue(country.code, forKeyPath: "code")
        countryObject.setValue(country.continent, forKeyPath: "continent")
        countryObject.setValue(country.continentCode, forKeyPath: "continentCode")

        countryObject.currency = currencyObject
      }
    }

    do {
      try managedContext.save()
    } catch let error as NSError  {
      print("Could not save \(error), \(error.userInfo)")
    }
}

更新:

感謝@Wain給我的想法。 基本上我所做的是解決在核心數據中保存重復數據的問題,我在JSON文件中包含了一個GUID。 每次代碼讀取JSON文件時,它都會將GUID保存到NSUserDefault並將數據保存到核心數據中。 當它想在下一次構建中再次讀取JSON文件時,它將檢查GUID是否與先前保存的GUID相同。 如果不同,代碼將讀取JSON文件並重復上述過程。 如果沒有,它將繼續並忽略它。

func requestCurrenciesData() {
    getCurrenciesDataFromFileWithSuccess { (data) -> Void in
      var json: [String: AnyObject]

      do {
        json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! [String: AnyObject]

        guard let currencyData = CurrencyData(json: json) else {
          print("Error initializing object")
          return
        }

        self.currencies = currencyData.currency!

        // Checking the JSON's id is same as previous read
        let defaults = NSUserDefaults.standardUserDefaults()
        if let id = defaults.stringForKey("id")
        {
          if id == currencyData.id {
            let notification = NSNotification(name: "CurrenciesDataUpdate", object: nil)
            NSNotificationCenter.defaultCenter().postNotification(notification)

            return
          }
        }

        self.persistCurrencyDataForId(currencyData.id)

        let notification = NSNotification(name: "CurrenciesDataUpdate", object: nil)
        NSNotificationCenter.defaultCenter().postNotification(notification)
      } catch {
        print(error)
        return
      }
   }
}

func persistCurrencyDataForId(id: String) {
    // Save the new JSON's id into NSUserDefaults
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(id, forKey: "id")

    // Delete all the records in existing table
    deleteRecordsFromEntity("Country")
    deleteRecordsFromEntity("Currency")

    // Insert the new records
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    let currencyEntity = NSEntityDescription.entityForName("Currency", inManagedObjectContext: managedContext)
    let countryEntity = NSEntityDescription.entityForName("Country", inManagedObjectContext: managedContext)

    for currency in currencies {
      let currencyObject = CurrencyCore(entity: currencyEntity!, insertIntoManagedObjectContext: managedContext)

      currencyObject.setValue(currency.code, forKeyPath: "code")
      currencyObject.setValue(currency.name, forKeyPath: "name")

      for country in currency.country! {
        let countryObject = CountryCore(entity: countryEntity!, insertIntoManagedObjectContext: managedContext)

        countryObject.setValue(country.name, forKeyPath: "name")
        countryObject.setValue(country.code, forKeyPath: "code")
        countryObject.setValue(country.continent, forKeyPath: "continent")
        countryObject.setValue(country.continentCode, forKeyPath: "continentCode")

        countryObject.currency = currencyObject
      }
    }

    do {
      try managedContext.save()
    } catch let error as NSError  {
      print("Could not save \(error), \(error.userInfo)")
    }
  }

func deleteRecordsFromEntity(entityName: String) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let coordinator = appDelegate.persistentStoreCoordinator

    let fetchRequest = NSFetchRequest(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    do {
      try coordinator.executeRequest(deleteRequest, withContext: managedContext)
    } catch let error as NSError {
      print(error)
    }
 }

一般來說,你可以說'如果我在數據存儲中有任何貨幣條目,不要添加更多'。 這可以通過在第一次導入時添加一個標志來使用默認值或類似的東西來完成,但更好的選擇是檢查數據存儲以查看它是否有任何貨幣條目。 為此,請為currencyEntity創建一個獲取請求並使用countForFetchRequest:error:在繼續使用for currency in currencies { 如果計數大於零,那么您應該返回而不是處理循環。

為了提高效率,這個檢查實際上應該是在你下載和處理JSON之前...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM