1

我无法检索我的通讯录的姓氏。我只想按字母表中的每个字母检索姓氏。

这是我到目前为止的代码

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];
    }

}

它只向数组添加一个名称,我应该怎么做才能将它全部添加。对不起,我对 ios 开发还很陌生!

4

1 回答 1

1

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

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

您需要在循环之外分配数组(否则它只会包含一个对象),数组也必须是 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);
}
于 2012-04-19T02:54:37.540 回答