6

'我面临着使用字典对象根据键对值进行排序的问题。实际上我要存储的是,每个字典对象在该字典中具有不同的数据类型所有数据类型都作为字符串如何将此字符串类型转换为特定的数据类型并对其进行排序价格虎钳,我的代码和输出如下,请帮我解决这个问题。

-(IBAction)PriceSort:(id)sender
{
    NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:@"Price" ascending:true] ;
    NSArray *sa = [symbolArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
    NSLog(@"price=%@",sa);

}

输出 {

    volume = 2496752;

    Yield = "10.49";

    MarCap = 829;

    Price = "0.715";

    Symbol = SAIPI;

},
4

2 回答 2

10
 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price"
                                                 ascending:YES selector:@selector(localizedStandardCompare:)] ;

请更换这个并尝试,希望它的作品。

于 2013-03-23T08:23:46.210 回答
4
-(void)sort
{
    //This is the array of dictionaries, where each dictionary holds a record
    NSMutableArray * array; 
    //allocate the memory to the mutable array and add the records to the arrat

    // I have used simple bubble sort you can use any other algorithm that suites you
    //bubble sort
    //
    for(int i = 0; i < [array count]; i++)
    {
        for(int j = i+1; j < [array count]; j++)
        {
            NSDictionary *recordOne = [array objectAtIndex:i];
            NSDictionary *recordTwo = [array objectAtIndex:j];

            if([[recordOne valueForKey:@"price"] floatValue] > [[recordTwo valueForKey:@"remaining"] floatValue])
            {
                [array exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }   
    }

    //Here you get the sorted array
}

希望这可以帮助。

于 2013-03-23T08:23:23.757 回答