2011-04-02 142 views
1

我检索联系人姓名与此代码:排序按字母顺序ABRecords iPhone上

for(int i = 0 ; i < n ; i++) 
{ 
    Contact *c = [[Contact alloc] init]; 

    ABRecordRef ref = CFArrayGetValueAtIndex(all, i); 
    NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty); 
    NSString *lastName = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty); 
    c.firstName = firstName; //[NSString stringWithFormat:@"%@ %@", firstName, lastName]; 
    c.lastName = lastName; 

    [contacts addObject:c]; 

    [c release]; 
} 

有谁知道按字母顺序排序此列表的方法是什么?我已阅读sortedArrayUsingSelector:@selector(compare:),但我不知道该如何工作。

回答

2
NSSortDescriptor *mySorter = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES]; 
[contacts sortUsingDescriptors:[NSArray arrayWithObject:mySorter]]; 
[mySorter release]; 
+0

谢谢,你可能想编辑它到NSSortDescriptor。再次感谢! – 2011-04-02 22:30:12

+0

刚刚编辑。谢谢 – Jorge 2011-04-02 22:37:14

0

此方法将让您尊重用户的首选或姓氏排序首选项。

contacts = (bridgedPeople as [ABRecord]).sort { 
    (person1, person2) -> Bool in 
    return .CompareLessThan == ABPersonComparePeopleByName(person1, person2, ABPersonGetSortOrdering()) 
} 

人提示:粗体,你排序上的名称的一部分;否则当你混合有[没有名字,没有姓氏,名字和姓氏]的联系人时,它会变得混乱