Swift - 从CoreData加载/保存会生成重复的条目

时间:2018-05-31 22:23:16

标签: ios swift core-data

我遇到了一个问题,我可以在Swift中为我的iOS应用程序保存和加载CoreData,但我遇到了一个问题,我试图保护重复条目,但它似乎不起作用。谁能告诉我哪里出错了?谢谢!

我的ViewController类:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource {

    @IBOutlet weak var headerLabel:UILabel!
    @IBOutlet weak var myTableView: UITableView!

    var lenders = [LenderData]()
    var lendersTemp = [LenderData]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.myTableView.rowHeight = 90
        myTableView.delegate = self
        myTableView.dataSource = self

        let fetchRequest: NSFetchRequest<LenderData> = LenderData.fetchRequest()

        do {
            let lenders = try PersistenceService.context.fetch(fetchRequest)
            self.lenders = lenders
        } catch {
            // Who cares....
        }


        downloadJSON {
            for tempLender in self.lendersTemp {
                if !self.lenders.contains(where: {$0.id == tempLender.id}) {
                    self.lenders.append(tempLender)
                }
            }
            self.lendersTemp.removeAll()
            PersistenceService.saveContext()
            self.myTableView.reloadData()
        }
    }

    func downloadJSON(completed: @escaping () -> ()) {
        let url = URL(string: "https://api.kivaws.org/v1/loans/newest.json")

        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print("JSON not downloaded")
            } else {
                if let content = data {
                    do {
                        let myJSONData = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        var imageID:Int64 = -1
                        var country:String = "N/A"
                        var latLongPair:String = "0.000000 0.000000"
                        var town:String = "N/A"

                        if let loans = myJSONData["loans"] as? NSArray {
                            for i in 0...loans.count-1 {
                                if let lender = loans[i] as? NSDictionary {
                                    if let imageData = lender["image"] as? NSDictionary { imageID = imageData["id"] as! Int64 }
                                    if let countryData = lender["location"] as? NSDictionary {
                                        country = countryData["country"] as! String
                                        town = countryData["town"] as! String
                                        if let geo = countryData["geo"] as? NSDictionary {
                                            latLongPair = geo["pairs"] as! String
                                        }
                                    }
                                    let newLender = LenderData(context: PersistenceService.context)
                                    newLender.id = lender["id"] as! Int64
                                    newLender.name = lender["name"] as? String
                                    newLender.image_id = imageID
                                    newLender.activity = lender["activity"] as? String
                                    newLender.use = lender["use"] as? String
                                    newLender.loan_amount = lender["loan_amount"] as! Int32
                                    newLender.funded_amount = lender["funded_amount"] as! Int32
                                    newLender.country = country
                                    newLender.town = town
                                    newLender.geo_pairs = latLongPair
                                    self.lendersTemp.append(newLender)
                                }
                            }
                        }
                        DispatchQueue.main.async {
                            completed()
                        }
                    } catch {
                        print("Error occured \(error)")
                    }
                }
            }
        }
        task.resume()
    }
}

修改

添加了我填充lendersTemp数组

的部分代码

1 个答案:

答案 0 :(得分:0)

我在评论中引用了这篇文章:

  

所以......你在后台线程上附加self.lendersTemp但是在主线程上读取它。相反,摆脱它,只需通过已完成的函数传递数据。

这正是我所做的。这工作