从核心数据数组中删除重复的元素

时间:2019-02-07 12:24:16

标签: swift core-data

我已经将联系人的数据存储在核心数据实体中,并且我试图将数据存储在该实体的数组中并在表视图中填充数据,现在当我获取该数据时,我得到了重复数据。如何从核心数据实体的数组中删除重复的数据。这是我如何从实体获取数据的代码,

 func getAllContacts()
{
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Contacts")
    request.returnsObjectsAsFaults = false
    do {
        let result = try context.fetch(request)

        allContacts = result as! [Contacts]

        for contact in allContacts
        {
            let register = contact.register
            if register == "yes"
            {
                self.contactsCoreDataRavenNameArray.append(contact.name!)
                self.contactsCoreDataRavenNumberArray.append(contact.number!)
                self.contactsCoreDataRavenImageArray.append(contact.image!)
            }
            else {

                self.contactsCoreDataNonRavenNameArray.append(contact.name!)
                self.contactsCoreDataNonRavenNumberArray.append(contact.number!)
                self.contactsCoreDataNonRavenImageArray.append(contact.image!)
            }
            contactsCoreDataNameServer.append(contact.name!)
            contactsCoreDataNumberServer.append(contact.number!)
            contactsCoreDataImageServer.append(contact.image!)
        }

    } catch {

        print("Failed")
    }
}

这是我将api响应数据存储在我的核心数据实体中的方式,

func compareWithRavenServerContacts(_ refreshing: Bool) {

    if let token = LoginToken {
        let param = [
            "token" : token,
            "contacts" : numberArrayForServer,
            "names" : namesArrayForServer
            ] as [String : Any]

        print(param)
        if refreshing {
            DispatchQueue.main.async {
            topViewController()?.view.makeToastActivity(.center)
            }
        }

        ServerCall.makeCallWitoutFile(GetRavenContactsUrl, params: param, type: Method.POST, currentView: nil) { (response) in

            if let json = response {
                print(json)
                if json["success"].boolValue {
                    let data = json["data"].arrayValue
                    print(data.count,data)
                    var ravenContacts = [ContactStruct]()
                    var serverContacts = [ContactStruct]()
                    var NonRavenContacts = [ContactStruct]()

                    for item in data
                    {
                        let name = item["name"].stringValue
                        let phone = item["phone"].stringValue
                        let picture = item["picture"].stringValue
                        let register = item["is_register"].stringValue

                        let optData = try? self.updateContact(name: name, number: phone)
                        guard let data1 = optData else {
                            return
                        }
                        print(data1)

                        let appDelegate = UIApplication.shared.delegate as? AppDelegate
                        let context = appDelegate?.persistentContainer.viewContext
                        let entity = NSEntityDescription.entity(forEntityName: "Contacts", in: context!)
                        let user = NSManagedObject(entity: entity!, insertInto: context)

                        user.setValue(name, forKey: "name")
                        user.setValue(phone, forKey: "number")
                        user.setValue(register, forKey: "register")
                        user.setValue(picture, forKey: "image")

                        do {
                            try context?.save()
                            print("Saved successfully.")

                        } catch  {
                            print("Fail to save")
                        }

                        let contact = ContactStruct(name: name, number: phone, register: register, profilePic: picture, isSelected: false)

                        if register == "yes" {
                            ravenContacts.append(contact)
                        } else {
                            NonRavenContacts.append(contact)
                        }
                        serverContacts.append(contact)
                    }

                    self.contactsRaven = ravenContacts.sorted(by: { ($0.name < $1.name) })

                    self.contactsServer = serverContacts.sorted(by: { ($0.name < $1.name) })

                    self.contactsNonRaven = NonRavenContacts.sorted(by: { ($0.name < $1.name) })

                    self.getAllContacts()

                    self.contactsDevice = self.contactsServer

                    topViewController()?.view.hideToastActivity()
                }
                else
                {
                    topViewController()?.view.makeToast("Error!. Please try again", duration: 2.0, position: .center)
                    topViewController()?.view.hideToastActivity()
                }
            }
        }
    }
    else {
        DispatchQueue.main.async {
            topViewController()?.view.makeToast("Error!, Login Again To Call Services", duration: 2.0, position: .center)
            topViewController()?.view.hideToastActivity()
        }
    }
}

1 个答案:

答案 0 :(得分:0)

因此,如果contact.name和contact.number都是字符串,则很容易清除重复项。 您只需要致电:

let noDuplicatesNameArray = Array(Set(exampleNameArray))

我假设contact.image是UIImage。这有点棘手。最好,最干净的解决方案是将UIImages的名称存储在字符串数组中,并检查是否重复,然后从中构造新的图像数组。

如果由于某种原因您不能这样做,我为您制定了一个解决方案,您可以在其中检查UIImages数组是否存在重复项。请注意,我现在刚刚敲定了这段代码。某些人可能会发现它并不复杂。如果您也发现它过于复杂,请在SO中搜索更理想的答案。

因此,您有一个UIImages数组:

var imagesArray = [UIImage(named: "image1"), UIImage(named: "image1"), UIImage(named: "image1"), UIImage(named: "image2")]

您创建了一个新数组,您将在其中保存非重复图像:

var newImagesArray = [UIImage]()

这是从重复项中清除数组的函数:

    func clearDuplicates() {
    var set = Set<Data>()

    for image in imagesArray {
        let data = image?.pngData()
        set.insert(data!)
    }

    let noDuplicateArray = Array(set)

    for imgData in noDuplicateArray {
        let image = UIImage(data: imgData)
        newImagesArray.append(image!)
    }
    print("You have an array of UIImages with no duplicates!")
}

现在newImagesArray是imagesArray但没有重复项。让我知道是否有帮助!

有关从数组中删除重复项的更多信息,请参见this这样的答案。