2012-04-19 53 views
1

我无法检索我的地址簿的姓氏。我只想通过字母表中的每个字母来检索姓氏。Xcode,只检索地址簿姓氏与字母A(等等)

这是我的代码至今

ABAddressBookRef addressBook = ABAddressBookCreate(); 
totalPeople = (__bridge_transfer NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); 

NSString *aString = @"A"; 

for(int i =0;i<[totalPeople count];i++){ 
    ABRecordRef thisPerson = (__bridge ABRecordRef) 
    [totalPeople objectAtIndex:i]; 
    lastName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonLastNameProperty); 
} 

我不知道以后该怎么办,谢谢你看这个。

现在就是这个样子

ABAddressBookRef addressBook = ABAddressBookCreate(); 
totalPeople = (__bridge_transfer NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); 

NSString *aString = @"A"; 

for(int i =0;i<[totalPeople count];i++){ 
    ABRecordRef thisPerson = (__bridge ABRecordRef) 
    [totalPeople objectAtIndex:i]; 
    lastName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonLastNameProperty); 

    NSString *firstLetterOfCopiedName = [lastName substringWithRange: NSMakeRange(0,1)]; 
    if ([firstLetterOfCopiedName compare: aString options: NSCaseInsensitiveSearch] == NSOrderedSame) { 
     //This person's last name matches the string aString 
     aArray = [[NSArray alloc]initWithObjects:lastName, nil]; 
    } 

} 

它onlys增加了一个名字到阵列中,我应该怎么才能做补充说明了一切。 对不起,我是相当新的ios开发!

回答

1

您可以使用类似的东西,并将结果存储在数组中或返回结果。 (未测试)

NSString *firstLetterOfCopiedName = [lastName substringWithRange: NSMakeRange(0,1)]; 
if ([firstLetterOfCopiedName compare: aString options: NSCaseInsensitiveSearch] == NSOrderedSame) { 
    //This person's last name matches the string aString 
} 

您需要ALLOC环路(否则将只包含一个对象)外的数组,数组也必须是一个NSMutableArray(因此它可以被修改)。这里是一个例子:

ABAddressBookRef addressBook = ABAddressBookCreate(); 
totalPeople = (__bridge_transfer NSMutableArray*)ABAddressBookCopyArrayOfAllPeople(addressBook); 

NSString *aString = @"A"; 

//This is the resulting array 
NSMutableArray *resultArray = [[NSMutableArray alloc] init]; 

for(int i =0;i<[totalPeople count];i++){ 
    ABRecordRef thisPerson = (__bridge ABRecordRef) 
    [totalPeople objectAtIndex:i]; 
    lastName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonLastNameProperty); 

    NSString *firstLetterOfCopiedName = [lastName substringWithRange: NSMakeRange(0,1)]; 
    if ([firstLetterOfCopiedName compare: aString options: NSCaseInsensitiveSearch] == NSOrderedSame) { 
     //This person's last name matches the string aString 
     [resultArray addObject: lastName]; 
    } 

} 

//print contents of array 
for(NSString *lastName in resultArray) { 
    NSLog(@"Last Name: %@", lastName); 
} 
+0

非常感谢你,我更新了代码。你能再看一遍,请告诉我我做错了什么。 – 2012-04-19 03:09:17

+0

已更新我的回答 – danielbeard 2012-04-19 03:28:45

+0

哇这个作品,非常感谢你帮助我! – 2012-04-19 03:38:42