对NSArray结果进行排序

时间:2015-01-15 07:21:54

标签: ios objective-c sorting nsarray

你如何对NSArray进行排序,我正在尝试这种方式但是得到了结果。

这是我正在使用的代码。

- (void)fetchedData:(NSData *)responseData
{
    NSLog(@"Key to sort = %@",keyToSort);
    NSError* error;
    NSDictionary *mainDic = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSArray *mainArr = [mainDic objectForKey:@"data"];
    // Sortion
    NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:keyToSort ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObject:valueDescriptor];
    NSArray *sortedArray = [mainArr sortedArrayUsingDescriptors:descriptors];

    for (int i = 0; i < [sortedArray count]; i++)
    {
        NSDictionary *subDic = [sortedArray objectAtIndex:i];
        [rankNumber addObject:[subDic valueForKey:keyToSort]]; // rankNumber is an Array
    }
}

OutPut

0
1
10
11
12
2
3
4
5
6
7
8
9

任何想法或建议,请帮助解决此问题

1 个答案:

答案 0 :(得分:3)

使用以下行:

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

而不是

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:keyToSort ascending:YES];