[英]IOS need to sort an array of dictionaries value based on key price
我正面臨着使用字典對象基於鍵對值進行排序的問題。 實際上我存儲的是,每個字典對象在該字典中具有不同的數據類型所有數據類型作為字符串如何將此字符串類型轉換為特定數據類型並對其進行排序,我的代碼和輸出信號如下,請幫我這個。
-(IBAction)PriceSort:(id)sender
{
NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:@"Price" ascending:true] ;
NSArray *sa = [symbolArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
NSLog(@"price=%@",sa);
}
out put {
volume = 2496752;
Yield = "10.49";
MarCap = 829;
Price = "0.715";
Symbol = SAIPI;
},
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price"
ascending:YES selector:@selector(localizedStandardCompare:)] ;
請替換這個並嘗試,希望它的作品。
-(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
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.