1.首先要在Frameworks中添加“AddressBook.framework”
2.自定义联系人类
#import <Foundation/Foundation.h>
@interface ZQPerson : NSObject {
NSString *firstName;
NSString *lastName;
NSString *fullName;
NSString *phone;
NSString *email;
}
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic, retain) NSString *fullName;
@property (nonatomic, retain) NSString *phone;
@property (nonatomic, retain) NSString *email;
@end
#import "ZQPerson.h"
@implementation ZQPerson
@synthesize firstName;
@synthesize lastName;
@synthesize fullName;
@synthesize phone;
@synthesize email;
- (void) dealloc {
[firstName release];
[lastName release];
[fullName release];
[phone release];
[email release];
[super dealloc];
}
@end
3.通讯录工具类
#import <Foundation/Foundation.h>
#import "ZQPerson.h"
@interface ZQAddressBookTool : NSObject {
}
+ (NSMutableArray *) getAddressBookList;
@end
#import "ZQAddressBookTool.h"
#import "TaGeDemoViewController.h"
@implementation ZQAddressBookTool
+ (NSMutableArray *) getAddressBookList {
NSMutableArray *personArray = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
// NSMutableArray *array = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSString *firstName;
NSString *lastName;
NSString *fullName;
personArray = (NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
for (id *person in personArray) {
ZQPerson *p = [[ZQPerson alloc] init];
firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
firstName = [firstName stringByAppendingFormat:@""];
lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
fullName = [firstName stringByAppendingFormat:@"%@",lastName];
p.firstName = firstName;
p.lastName = lastName;
p.fullName = fullName;
ABMultiValueRef phones = (ABMultiValueRef) ABRecordCopyValue(person,kABPersonPhoneProperty);
for (int i = 0; i < ABMultiValueGetCount(phones); i ++) {
NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
p.phone = phone;
[phone release];
}
ABMultiValueRef emails = (ABMultiValueRef) ABRecordCopyValue(person,kABPersonEmailProperty);
for (int i = 0; i < ABMultiValueGetCount(emails); i ++) {
NSString *email = (NSString *)ABMultiValueCopyValueAtIndex(emails, i);
p.email = email;
[email release];
}
[firstName release];
[lastName release];
[fullName release];
[array addObject:p];
[p release];
}
return array;
} // getAddressBookList
@end
4.调用方法
NSMutableArray *persons = [ZQAddressBookTool getAddressBookList];
for (ZQPerson *person in persons) {
NSLog(person.fullName);
NSLog(person.phone);
NSLog(person.email);
[persons release];
}
[persons release];