2014-02-19 53 views
0

我有一個包含關鍵字@"Category"的對象(字典)數組。我必須通過由該密鑰開始的特定密鑰對其進行排序。例如,如果objects[@"Category"]: A, B ,C ,D ,E ,F ,G , H etc.和用戶選擇「按C排序」中的值,則需要按照以下對象重新排序根數組:[@"Category"]至:C,D,E,F,G,H,A,B - 或者 - C ,A,B,D,E,F,G,H。從特定值開始對字典進行排序

我希望很清楚我的目標是什麼。我試過了:

// sortedPosts2 = [self.objects sortedArrayUsingComparator:^(PFObject *object1, PFObject *object2) { 
//   return [object1[@"Category"] compare:object2[@"Category"] options:NSOrderedAscending]; 
// }]; 


// NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:category ascending:YES]; 
// sortedPosts2 = [self.objects sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]]; 


    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop]; 
} 
+0

在你的代碼似乎沒有什麼應對所選的排序項... – Wain

+0

sortDescriptorWithKey :類別,其中category是用戶選擇的字符串 – snksnk

回答

1

我能想到的最簡單的方法就是排序塊。然後你可以手動調整數組比較值。這應該適用於任何大小的字符串Category。您可能需要改變周圍的比跡象或遞增/遞減的回報,我總是搞不清楚了上升/下降更大...

NSArray *array; 
NSString *userSelectedValue = @"C"; 
array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
    NSString *category1 = [[(NSDictionary*)obj1 objectForKey:@"Category"] lowercaseString]; 
    NSString *category2 = [[(NSDictionary*)obj2 objectForKey:@"Category"] lowercaseString]; 

    //Now check if either category's value is less than the user selected value 
    NSComparisonResult result1 = [category1 compare:[userSelectedValue lowercaseString]]; 
    NSComparisonResult result2 = [category2 compare:[userSelectedValue lowercaseString]]; 

    if(result1 == result2) 
    { 
     return [category1 compare:category2]; 
    } 
    else if(result1 > result2) 
    { 
     return NSOrderedDescending; 
    } 
    else 
     return NSOrderedAscending; 
}]; 
相關問題