iPhone通讯录中的联系人排序
Posted
技术标签:
【中文标题】iPhone通讯录中的联系人排序【英文标题】:Sorting of contacts from iPhone address book 【发布时间】:2012-05-30 01:51:12 【问题描述】:我有一个使用通讯录的应用程序。我正在尝试使用
显示地址簿中的姓名排序列表sortedArray = [arr_contactList sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
然后当用户选择其中一个联系人时,会显示其电话号码。
我可以对 iPhone 通讯簿电话号码进行排序。
我使用以下方法对电话号码进行排序:
ABRecordRef source = ABAddressBookCopyDefaultSource(ab);
NSArray *thePeople = (NSArray*)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(ab, source, kABPersonSortByFirstName);
NSString *name;
for (id person in thePeople)
name = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
NSString* num = (NSString*)ABMultiValueCopyValueAtIndex(phones, j);
CFStringRef locLabel1 = ABMultiValueCopyLabelAtIndex(phones, j);
NSString *phoneLabel1 =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel1);
[tempPhoneArray addObject:num];
但我的实际问题是,我的姓名数组的联系人列表顶部以特殊字符开头,当我选择电话号码时,排序的联系人列表以字母 A 开头。所以我得到了错误的电话号码。
如何匹配这两种排序 - 名称排序和数字排序?
【问题讨论】:
【参考方案1】:在此示例中,您将创建 27 个数组,每个字母 1 个,但该概念可应用于特殊字符与大写/小写的任何检查。希望这会有所帮助。
const int capacity = 27;
NSMutableArray *subArrays = [NSMutableArray array];
//Prepopulate the subArray with 26 empty arrays
for(int i = 0; i < capacity; i++)
[subArrays addObject:[NSMutableArray array]];
char currFirstLetter = 'a';
for(int i = 0; i < sortedArray.count; i++)
NSString *currString = [[sortedArray objectAtIndex:i] lowercaseString];
NSLog(@"%@", currString);
NSLog(@"%c", [currString characterAtIndex:0]);
NSLog(@"%c", currFirstLetter);
if([currString characterAtIndex:0] == currFirstLetter)
//65 is the position of 'a' in the ascii table, so when we subtract 97, it correlates to 0 in our array.
[[subArrays objectAtIndex:currFirstLetter-97] addObject:[sortedArray objectAtIndex:i]];
else if([currString characterAtIndex:0] < 65 || ([currString characterAtIndex:0] > 90 && [currString characterAtIndex:0] < 97) || [currString characterAtIndex:0] > 122)
//If it's a symbol (65-90 are uppercase, 97-122 are lowercase)
[[subArrays objectAtIndex:26] addObject:[sortedArray objectAtIndex:i]];
//Increment the letter we're looking for, but decrement the count to try it again with the next letter
else
currFirstLetter++;
i--;
【讨论】:
子数组有哪些?代码在 [subArrays objectAtIndex:26] 崩溃:( 我添加了实例化子数组的代码,对此感到抱歉。 感谢您的代码。但是使用这段代码,数组是排序的,列出了顶部以特殊字符开头的联系人。最后我想要特殊字符,与 iPhone 原生地址簿完全相似。 :(如何实现? 当您在 for 循环中进行比较时,if 语句决定了要做什么。因此,通过获取排序数组并对其进行迭代,您可以确定它是否是特殊字符。如果是特殊字符,就区别对待,如果不是,就和普通字符一样处理。以上是关于iPhone通讯录中的联系人排序的主要内容,如果未能解决你的问题,请参考以下文章