iPhone 添加删除联系人

来源:互联网 发布:菜鸟网络的商业模式 编辑:程序博客网 时间:2024/04/29 22:28
 -(IBAction)onClickbutton:(id)sender
    {
        NSMutableArray* personArray = [[[NSMutableArray alloc] init] autorelease];
        ABAddressBookRef addressBook = ABAddressBookCreate();
        NSString *firstName, *lastName, *fullName;
        personArray = (NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
        if ([sender tag]==0) {

            for (id *person in personArray)
            {
                firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
                firstName = [firstName stringByAppendingFormat:@" "];
                lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);  
                fullName = [firstName stringByAppendingFormat:@"%@",lastName];
                NSLog(@"===%@",fullName);
                ABMultiValueRef phones = (ABMultiValueRef) ABRecordCopyValue(person, kABPersonPhoneProperty);
                for(int i = 0 ;i < ABMultiValueGetCount(phones); i++)
                {
                    NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
                    NSLog(@"===%@",phone);
                }
                ABMultiValueRef mails = (ABMultiValueRef) ABRecordCopyValue(person, kABPersonEmailProperty);
                for(int i = 0 ;i < ABMultiValueGetCount(mails); i++)
                {
                    NSString *mail = (NSString *)ABMultiValueCopyValueAtIndex(mails, i);
                    NSLog(@"==%@",mail);
                }      
            }  
        }else {
            //删除信息
            //返回所有联系人到一个数组中
            CFArrayRef personArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
            CFIndex personCount = ABAddressBookGetPersonCount(addressBook);
              for (int i =0;i<personCount;i++){
                  ABRecordRef ref = CFArrayGetValueAtIndex(personArray, i);
                  CFStringRef firstName1 = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
                  CFStringRef lastName1 = ABRecordCopyValue(ref, kABPersonLastNameProperty);
                  NSString *contactFirstLast = [NSString stringWithFormat: @"%@%@", (NSString *)firstName1,(NSString *)lastName1];
                if ([contactFirstLast isEqualToString:@"徐梦"]) {
                    //删除联系人
                    ABAddressBookRemoveRecord(addressBook, ref, nil);
                }
            }
            //保存电话本
            ABAddressBookSave(addressBook, nil); 
            //释放内存
            //CFRelease(personRef);
    //        CFRelease(addressbookRef);
        }
    }