ABAddressBookRemoveRecord();偶尔不会按预期删除

时间:2014-09-07 17:42:45

标签: ios objective-c addressbook

我编写了一个可以访问addressbook的应用,用户应该能够从应用中删除该联系人,并且会从addressbook

中删除该联系人

有时候这种情况不会发生,虽然在跟踪时,一切都按预期工作,我会在删除后立即通知ABAddressBookRegisterExternalChangeCallback();,但是当我在电话上联系应用时,联系人总数保持不变,联系仍然存在,而不是删除。

以下是删除代码

// this method takes and NSManagedObject which holds the id of the person that should be deleted

- (void)deleteContactFromAddressBook:(NSManagedObject *)object
{
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    NSNumber *contactID = [object valueForKey:@"contactID"];
    ABRecordRef contactRef = ABAddressBookGetPersonWithRecordID(addressBook, [contactID intValue]);

    NSString *firstName = (__bridge NSString *)ABRecordCopyValue(contactRef,
                                                             kABPersonFirstNameProperty);
    NSString *lastName = (__bridge NSString *)ABRecordCopyValue(contactRef,
                                                            kABPersonLastNameProperty);
    if (!lastName) {
        lastName = @"";
    }
    NSLog(@"contact to be deleted - Name: %@" ,[firstName stringByAppendingString:lastName]);

    BOOL deleteCheck = ABAddressBookRemoveRecord(addressBook, contactRef, NULL);

    BOOL saveCheck = ABAddressBookSave(addressBook, NULL);

    NSLog(@"delete check = %hhd ---------- save check = %hhd", deleteCheck, saveCheck);
    NSLog(@"Contact Deleted with id: %@", contactID);
}

如果您需要进一步解释,请不要犹豫。我对这种意想不到的行为感到非常沮丧,我不知道在哪里看。

谢谢。

1 个答案:

答案 0 :(得分:1)

我可能错了,因为到目前为止,我只为OSX写过,我确实有类似的问题,我最终解决了。 (见下面的链接)
我预感你的addressBook对象只是一个本地副本。我发现我必须使用ABAddressBook *addressBook =[ABAddressBook sharedAddressBook];获取地址簿并使用其中的记录,与[addressBook save];一样完成您的iOS使用情况可能会有所不同。 (How can I get the values I set for custom properties in AddressBook to persist?