我想知道是否有人可以帮助解决我面临的问题。我已经使用标准方式检索了电话联系人(我必须按姓氏排序)
NSMutableArray *contactArray = [NSMutableArray array];
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFMutableArrayRef peopleMutable = CFArrayCreateMutableCopy(kCFAllocatorDefault,CFArrayGetCount(people), people);
CFArraySortValues(peopleMutable, CFRangeMake(0,
CFArrayGetCount(peopleMutable)),
(CFComparatorFunction)ABPersonComparePeopleByName, (void
*)kABPersonSortByLastName);
NSArray *allPeopleArray = (NSArray *)peopleMutable;
我遍历每条记录并用 kABPersonFirstNameProperty、kABPersonLastNameProperty、kABPersonEmailProperty、kABPersonPhoneProperty 填充 NSMutableDictionary。一些联系人没有名字或姓氏。因此,我确实检查了它们并使用 [NSNull null] 填充 MutableDictionary 用于 lastName 的 firstName。现在我需要对这个 MutableArray 进行排序。我使用 NSSortDescriptor 进行排序
NSSortDescriptor *aSortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
NSSortDescriptor *aSortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
[listToSort sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor1, aSortDescriptor2, nil]];
[aSortDescriptor1 release];
[aSortDescriptor2 release];
当我 NSLog listToSort 列表正确排序时。
然后我将这个排序的可变数组传递给这个方法,它基本上创建了一个 sectionList 用于在 UItableview 上显示
-(void)setupSectionList:(NSMutableArray *)contactList {
sectionNames = [[NSMutableArray alloc]init];
sectionData = [[NSMutableArray alloc]init];
NSString *previous=@"";
for (NSDictionary *dict in contactList) {
NSString *lastName = [dict objectForKey:@"lastName"];
NSString *firstName = [dict objectForKey:@"firstName"];
NSString *firstLetter = nil;
if ([dict objectForKey:@"lastName"] != [NSNull null]) {
firstLetter = [lastName substringToIndex:1];
}else if ([dict objectForKey:@"firstName"] != [NSNull null]) {
firstLetter = [firstName substringToIndex:1];
}
//Get the first Letter
if (firstLetter) {
//Add the letter to sectioNames when it is different
if (![firstLetter isEqualToString:previous]) {
previous = firstLetter;
[sectionNames addObject:[firstLetter uppercaseString]];
//Now add a new array to our array of arrays
NSMutableArray *oneSection = [NSMutableArray array];
[sectionData addObject:oneSection];
}
//Add this dictionary to the last section array
[[sectionData lastObject] addObject:dict];
}
}
}
这是排序搞砸的地方。这是一个例子。我的联系人只有一个名字作为名字,没有别的。我还有另外两个联系人 John Appleseed 和 William Frank。当我从上面的代码中对 sectionData 进行 NSLog 记录时,我看到第一个字母为 F、A、F。我希望看到 A、F。有人可以帮我解决这个问题吗?提前感谢您的帮助。