无法从通用功能的CNMutableContact中删除项目

时间:2019-02-13 04:52:35

标签: swift generic-programming cncontact

我希望允许用户在显示原始联系人并根据他们选择的内容从我的编辑联系人中删除之后从联系人中删除元素(例如CNPhoneNumberCNEmailAddresses)。

即使我有一个可变的联系人,并且在代码中使用键中的可变数组,返回的已编辑联系人也不会删除该元素。

我在这里做什么错了?

这是我的通用函数(除了上面列出的问题,它可以正常运行并运行)

private func removeFromEditedContact<T:NSString>(labeledValueType:T, with key:String,from contact:CNContact,to toContact:CNContact, at indexPath:IndexPath) -> CNContact {

    let mutableContact = toContact.mutableCopy() as! CNMutableContact


    //what detail are we seraching for in the contact
    if let searchingArray = contact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>] {
        let searchValue = searchingArray[indexPath.row].value
        //if detail is present in our mutable contact remove it
        var labeledValueToChange = mutableContact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>]

        if let index = labeledValueToChange?.index(where: {$0.value == searchValue})  {
            labeledValueToChange?.remove(at: index)

        }
    }
    return mutableContact
}

1 个答案:

答案 0 :(得分:1)

该联系人没有被修改,因为您只是从创建的可变数组中删除该值。从labeledValueToChange中删除该值后,您必须将其分配回该联系人,如下所示:

contact.setValue(labeledValueToChange, forKey: key)

如果原始联系人是您要修改的联系人,您也可以将其直接作为inout参数传递给函数。我尝试了您的功能,它的工作原理如下:

private func removeFromEditedContact<T:NSString>(labeledValueType:T, with key:String,from contact:inout CNMutableContact, at indexPath:IndexPath) -> CNMutableContact {

        //what detail are we seraching for in the contact
        if let searchingArray = contact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>] {

            let searchValue = searchingArray[indexPath.row].value
            //if detail is present in our mutable contact remove it
            var labeledValueToChange = contact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>]

            if let index = labeledValueToChange?.index(where: {$0.value == searchValue})  {
                labeledValueToChange?.remove(at: index)
            }


            contact.setValue(labeledValueToChange, forKey: key)
        }

        return contact
    }