2017-07-17 58 views
0

我從網絡獲取電話和JSON解析它的數據爲:如何從一個陣列的數據複製到核心數據實體

Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default) 
      .responseJSON { response in 

       if let status = response.response?.statusCode { 
        switch(status){ 
        case 200: 

         self.allResponse = response.result.value as! NSDictionary 

         if let categories = self.allResponse.value(forKey: "categories") as? [[String: AnyObject]] { 
          for category in categories { 
           self.categories.append(Category(dict: category)) 
          } 
         } 

         self.collectionView.reloadData() 
        default: 
         print("error with response status: \(status)") 
        } 
       } 
     } 

的代碼獲取數據,併成功地解析它。現在我想將這些數據保存在我所做的CoreData實體中。我有var categories = [Category]()中的所有類別,我想用魔法記錄將它複製到核心數據的實體中。我之前在CoreData上保存了值,但它們是一個一個的。現在我已經將所有數據堆棧存儲在一個數組中,我需要將其存儲在coredata中。我怎樣才能做到這一點?

回答

0

您可以像這樣保存數據。

func saveToDataBase(_ saveData:[Category]){ 
     for data1 in data{ 

      let request:NSFetchRequest<Category> = Category.fetchRequest() 
      request.predicate = NSPredicate(format: "id == %@", (id to check previously save or not) 

      do { 
       let count = try managedObjectcontext.count(for: request) 

       if count == 0 { 
        // save data according to your requirement. 
        print(data1) 
       }else{ 

        //if anything you want to update then wright here 
       } 

      }catch{ 
       let error = error as NSError 
       print("\(error)") 
      } 
     } 
    } 

我已經回答了這個問題,希望它能幫助你。如果你想在這裏看到coredata經理,我已經發了sample project