2011-04-02 83 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()) 
} 

人提示:粗體,你排序上的名稱的一部分;否則當你混合有[沒有名字,沒有姓氏,名字和姓氏]的聯繫人時,它會變得混亂