2013-10-21 187 views
3

我有一個字母數字名稱的列表,當我在A-Z (0-9 A-Z)之前的位置下面運行代碼時。字母數組排序

我該如何讓這個NSSortDescriptor把數字放在數組末尾(A-Z 0-9)

NSSortDescriptor *sortNameSortDescriptor = 
[NSSortDescriptor sortDescriptorWithKey:@"sortName" 
ascending:YES 
selector:@selector(localizedStandardCompare:)]; 

NSArray *sortedArray = [sortSectionsArray sortedArrayUsingDescriptors:@[ sortNameSortDescriptor ]]; 

回答

2

也許你可以使用基於NSComparator的排序描述符?

粗線條

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"sortName" ascending:YES 
    comparator:^NSComparisonResult(NSString* obj1, NSString* obj2) 
    { 
      //Return negative number, zero or positive based on 
      //first letter being number or alpha. 
      //If obj1 starts with a letter and obj2 starts with a number then 
      //return NSOrderedAscending. . . otherwise just return [obj1 comppare:obj2]; 

      //To test if first chararacter is a letter: 

      NSRange first = [obj1 rangeOfComposedCharacterSequenceAtIndex:0]; 
      NSRange match = [obj1 rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] options:0 range:first]; 
      if (match.location != NSNotFound) {//Implement above comment} 
    }];