如何使用objective-c从iPhone中的地址簿中删除联系人?

时间:2009-11-25 22:00:12

标签: iphone cocoa-touch

我想删除iPhone中地址簿中的联系人,我们该怎么做?

谢谢

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

以下是执行相同操作的示例代码:

- (void)delAllContacts {
    ABAddressBookRef addressBook = CFBridgingRetain((__bridge id)(ABAddressBookCreateWithOptions(NULL, NULL)));
    int count = ABAddressBookGetPersonCount(addressBook);
    if(count==0 && addressBook!=NULL) { //If there are no contacts, don't delete
        CFRelease(addressBook);
        return;
    }
    //Get all contacts and store it in a CFArrayRef
    CFArrayRef theArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
    for(CFIndex i=0;i<count;i++) {
        ABRecordRef person = CFArrayGetValueAtIndex(theArray, i); //Get the ABRecord
        BOOL result = ABAddressBookRemoveRecord (addressBook,person,NULL); //remove it
        if(result==YES) { //if successful removal
            BOOL save = ABAddressBookSave(addressBook, NULL); //save address book state
            if(save==YES && person!=NULL) {
                CFRelease(person);
            } else {
                NSLog(@"Couldn't save, breaking out");
                break;
            }
        } else {
            NSLog(@"Couldn't delete, breaking out");
            break;
        }
    }
    if(addressBook!=NULL) {
        CFRelease(addressBook);
    }
}

答案 2 :(得分:0)

+(BOOL)removedRecordFromAddressBookWithFirstValue:(NSString *)fullName{
    BOOL recordRemoved=NO;
    CFErrorRef err;
    ABAddressBookRef addressBook=
    ABAddressBookCreateWithOptions(NULL,&err);
    CFArrayRef people=ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople=ABAddressBookGetPersonCount(addressBook);
    NSString *currRecordFullName=[[NSString alloc] init];
    /*Invariant: No record with the name fullName has been
      found so far.*/
    for(int i=0;i<nPeople;i++){
        ABRecordRef ref=CFArrayGetValueAtIndex(people,i);
        CFErrorRef error=NULL;
        currRecordFullName=nil;
        currRecordFullName=[[NSString alloc] init];
        currRecordFullName=
        (__bridge NSString  *)ABRecordCopyCompositeName(ref);
        if([currRecordFullName isEqualToString:fullName]){
            /*The record to be deleted has been found.*/
            ABAddressBookRemoveRecord(addressBook,ref,&error);
            ABAddressBookSave(addressBook,&error);
            CFRelease(ref);
            CFRelease(addressBook);
            if(error!=NULL){
                CFStringRef errorDesc=CFErrorCopyDescription(error);
                NSLog(@"Failed to remove record: %@",errorDesc);
                CFRelease(errorDesc);
            }else{
                NSLog(@"Record removed");
                recordRemoved=YES;
            }
            break;
        }else{;}
    }
    return recordRemoved;
}