2013-03-23 178 views
6

對基於密鑰使用字典對象排序值的字典值進行排序。其實我正在存儲的是,每個字典對象在該字典中具有不同的數據類型,所有的數據類型都以字符串的形式如何將此字符串類型轉換爲特定的數據類型並對其進行排序,我的代碼和輸出是波紋管,請幫助我解決這個問題。IOS需要根據關鍵字價格

-(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; 

}, 
+0

字典中的數據類型有多不同,你可以向他們展示嗎? – 2013-03-23 08:07:29

回答

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

請替換這個並嘗試,希望它的作品。

+0

謝謝你krish它的工作 – Vijay 2013-03-24 18:44:14

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 
} 

希望這有助於。

+0

謝謝kunal – Vijay 2013-03-24 18:45:23