Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an NSArray containing numbers as NSString objects. ie.

[array addObject:[NSString stringWithFormat:@"%d", 100]];

How do I sort the array numerically? Can I use compare:options and specify NSNumericSearch as NSStringCompareOptions? Please give me an example/sample code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
683 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the example code given for the sortedArrayUsingFunction:context: method which should work fine for NSStrings too as they also have the intValue method.

// Place this functions somewhere above @implementation
static NSInteger intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

// And used like this
NSArray *sortedArray; 
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...