我可以在没有ABPersonViewController的情况下编辑ABaddressBook中的现有联系人吗?

时间:2014-12-01 12:08:05

标签: ios objective-c abaddressbook abpersonviewcontroller

我创建了一个自定义地址簿,用于复制带有联系人的本地地址簿列表。现在,在详细视图控制器中,我设法添加了一个新联系人并从本地地址簿中删除了现有联系人。我想编辑现有联系人并将更改保存到本机地址簿。

1 个答案:

答案 0 :(得分:0)

以下示例假定您具有要在recordID中更改的记录的ID, 并且您希望将其地址更改为存储在addressDictionary中的新地址。

CFErrorRef error = nil;
const ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions (NULL, &error);
if (addressBookRef != nil) {
    ABRecordRef record = ABAddressBookGetPersonWithRecordID(addressBookRef, recordID);
    if (record != nil) {
        ABMultiValueRef addressesRef = ABRecordCopyValue(record, kABPersonAddressProperty);
        if (addressesRef != nil) {
            // Addresses found
            ABMutableMultiValueRef tmpAddressesRef = ABMultiValueCreateMutableCopy(addressesRef);
            if (tmpAddressesRef != nil) {
                CFIndex addressIndex = ABMultiValueGetIndexForIdentifier (addressesRef,addressID);
                bool OK;
                OK = ABMultiValueReplaceValueAtIndex(tmpAddressesRef, (__bridge CFTypeRef)addressDictionary, addressIndex);
                if (OK) {
                    OK = ABRecordSetValue(record, kABPersonAddressProperty, tmpAddressesRef, &error);
                    if (OK) {
                        OK = ABAddressBookSave(addressBookRef, &error);
                        if (OK) {
                            // Do something
                        } else {
                            // Could not save address book
                        }
                    } else {
                        // Could not store modified address
                    }
                }
                else {
                    // Could not replace address
                }
                CFRelease(tmpAddressesRef);
            } // Mutable copy of addresses could be created
            else {
                // Could not create mutable copy of addresses
            }
            CFRelease(addressesRef);
        } else {
            // Did not find addresses
        }
    } else {
        // Could not read record
    }
    CFRelease(addressBookRef);
}
else {
    // Could not open address book
}