开发者

sortedArrayWithSelector and NSDictionnary on iOS

I have an array of NSDictionnary and I开发者_如何学JAVA would like to sort them by an int value (the key is named "age"). For exemple :

Dic1 : age = 30, sex = male; Dic2 : age = 24, sex = male;

Array : Dic1, Dic2;

Now with a compare method I would lik to have :

Array : Dic2, Dic1;

I tried lots of things but doesn't work. I as using NSSortDescriptor but it's only available since iOS 4.0 :(

Have you got a solution ? Thanks !

EDIT :

I wrote a compare method on NSDictionary category :

- (NSComparisonResult)compareGood:(NSDictionary *)otherObject 
{
    return [[self objectForKey:@"age"] compare:[otherObject objectForKey:@"age"]];
}

But I have this crash error : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFNumber compare:]: nil argument'


The documentation for NSSortDescriptor says:

Available in iOS 2.0 and later.

Likewise for the NSMutableArray method -sortUsingDescriptors:. You should be able to do this:

NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"age" 
                                                          ascending:YES]
                                                          autorelease];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:descriptor];

or, if myArray isn't mutable, do this for the second line:

NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜