English 中文(简体)
• 如何用数字对阵列控制器进行分类,以达到目标。
原标题:How to sort array controller alphabetically with numbers last in objective-c?

我有<条码>NSArrayController,我谨对内容进行分类,首先对英文字母进行分类,然后对数字和非英文性质的任何内容进行分类。

例如:A、B、C.Z、1、2、3、9、구、......

目前我只知道如何按字母顺序排列项目。 建议

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
        [dataController setSortDescriptors: [NSArray arrayWithObject: sort]];
最佳回答

您可使用<条形码>,根据您的需要定制这种算法。 举例来说,你可以优先使用具有以下文字的符号:

NSArray *assorted = [@"1 2 3 9 ; : 구 , 결 A B C Z ! á" componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *sorted = [assorted sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    /* NSOrderedAscending, NSOrderedSame, NSOrderedDescending */
    BOOL isPunct1 = [[NSCharacterSet punctuationCharacterSet] characterIsMember:[(NSString*)obj1 characterAtIndex:0]];
    BOOL isPunct2 = [[NSCharacterSet punctuationCharacterSet] characterIsMember:[(NSString*)obj2 characterAtIndex:0]];
    if (isPunct1 && !isPunct2) {
        return NSOrderedAscending;
    } else if (!isPunct1 && isPunct2) {
        return NSOrderedDescending;
    }
    return [(NSString*)obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];         
}];

http://English non-English之前的特性,足以作为备选办法使用NSDiacritic IntiveSearch NS CaseIntiveStarch,无需计算出任何算法。

如你需要支持SiOS,不设区块,可尝试<编码>。

问题回答

试验的另一个解决办法是,如果体力是可编码的:

  • test for both strings, if the first character is a latin (aka english) character
  • if both are, test if both starts either with a letter or a number. In both cases, leave it up the compare:
  • 否则,如果编号一开始,一开始写一封信,return NSOrderingAscending,其中一封信附有第一封信,另一封信是NSOrderingDescending

  • 如果两项指示都为t latin,请compare: 再次

  • if one is latin, and one not, return NSOrderingAscending if the latin is first, otherwise NSOrderingDescending

the code

NSArray *array = [NSArray arrayWithObjects:@"peach",@"apple",@"7",@"banana",@"ananas",@"5", @"papaya",@"4",@"구",@"결",@"1" ,nil];

array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSString *s1 = [obj1 substringToIndex:1];
    NSString *s2 = [obj2 substringToIndex:1];
    BOOL b1 = [s1 canBeConvertedToEncoding:NSISOLatin1StringEncoding];
    BOOL b2 = [s2 canBeConvertedToEncoding:NSISOLatin1StringEncoding];

    if ((b1 == b2) && b1) {//both number or latin char
        NSRange r1 = [s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
        NSRange r2 = [s2 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
        if (r1.location == r2.location ) { // either both start with a number or both with a letter
            return [obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch]; 
        } else {  // one starts wit a letter, the other with a number
            if ([s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == NSNotFound) {
                return NSOrderedAscending;
            }
            return NSOrderedDescending;
        }
    } else if((b1 == b2) && !b1){ // neither latin char
        return [obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];
    } else { //one is latin char, other not
        if (b1) return NSOrderedAscending;
        return NSOrderedDescending;
    }

}];
for (NSString *s in array) NSLog(@"%@", s);

ananas
apple
banana
papaya
peach
1
4
5
7
구
결

我不认为你可以做这种分类,而没有界定自己的比较职能。

To this aim, you could use sortedArrayUsingFunction:

[array sortedArrayUsingFunction:f context:userContext];

f 定义为:

NSInteger f(id num1, id num2, void *context)
{
   int v1 = [num1 intValue];
   int v2 = [num2 intValue];
   if (...)
     return NSOrderedAscending;
   else if (...)
     return NSOrderedDescending;
   else
     return NSOrderedSame;
}

If you prefer not creating function for doing this you could use the block-version of the method, sortedArrayUsingComparator:

[array sortedArrayUsingComparator: ^(id obj1, id obj2) {
                                             return NSOrderedSame;
                                   }];

以比较器为基础的某种描述器应当做到trick(注:未经测试)。

NSComparator cmp = ^(id str1, id str2) {

// Make your sorting
    if ( /* str1 before str2 */ )
    return NSOrderedAscending
    else if ( /* str2 after str1 */ )
    return NSOrderedDescending
    else 
    return NSOrderedSame
};

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey: sortKey ascending: YES comparator: cmp];

NSArrayController *ac = // ...

[ac setSortDescriptor: sd];

You of course have to define your own sort order algorithm - but this example should show how to use a sort descriptor for an array controller.

One thing is missing to answer properly to the question : NSNumericSearch

NSArray *assorted = [@"1 2 3 9 ; : 구 , 결 A B C Z ! á" componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *sorted = [assorted sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    /* NSOrderedAscending, NSOrderedSame, NSOrderedDescending */
    BOOL isPunct1 = [[NSCharacterSet punctuationCharacterSet] characterIsMember:[(NSString*)obj1 characterAtIndex:0]];
    BOOL isPunct2 = [[NSCharacterSet punctuationCharacterSet] characterIsMember:[(NSString*)obj2 characterAtIndex:0]];
    if (isPunct1 && !isPunct2) {
        return NSOrderedAscending;
    } else if (!isPunct1 && isPunct2) {
        return NSOrderedDescending;
    }
    return [(NSString*)obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch|NSNumericSearch]|;         
}];




相关问题
How do I sort enum members alphabetically in Java?

I have an enum class like the following: public enum Letter { OMEGA_LETTER("Omega"), GAMMA_LETTER("Gamma"), BETA_LETTER("Beta"), ALPHA_LETTER("Alpha"), private final String ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Sorting twodimensional Array in AS3

So, i have a two-dimensional Array of ID s and vote count - voteArray[i][0] = ID, voteArray[i][1] = vote count I want the top 3 voted items to be displayed in different colors, so i have a 2nd Array -...

Linq operations against a List of Hashtables?

I m working with a set of legacy DAO code that returns an IList, where each Hashtable represents the row of a dynamically executed SQL query. For example, the List might contain the following records/...

C++ Array Sort Me

Stuck on an array sorter. Have to sort numbers from largest to smallest. I m trying two loops (one nested in the other). Here s the code: int counter=0; // inner counter int counter2=0; // outer ...

Can I Nest OrderBy in .NET?

This doesn t seem to work as I intend. VB.NET: Dim x = Model.Discussions.OrderByDescending(Function(d) d.Messages.OrderByDescending(Function(m) m.Sent).First.Sent) For Each d As Discussion In x ....

sorting elements javascript

I m looking for a way to sort my elements, but it isn t as easy as it sounds. Please let me explain My elements are grouped per 6 elements (thumbnails), each x represents a thumbnail However all ...