2012-04-19 25 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