2013-03-13 61 views
2

我正在使用以下NSSortDescriptor代碼對數組進行排序。我目前正按價格排序,但也想限制價格。是否可以按價格分類,但只能顯示價格低於100的例子?如何使用NSSortDescriptor對NSMutableArray進行排序

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
             initWithKey: @"price" ascending: YES]; 

NSMutableArray *sortedArray = (NSMutableArray *)[self.displayItems 
                sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortDescriptor]]; 

[self setDisplayItems:sortedArray]; 

[self.tableView reloadData]; 
+0

你不能只將'NSArray'投射到'NSMutableArray'。使用'[array mutableCopy]' – Sebastian 2013-03-13 10:43:10

+0

塞巴斯蒂安是對的。一個NSArray將永遠是一個NSArray,只要它是一個子類的成員,在這種情況下,它總是該子類的成員。 – moonman239 2015-08-19 19:59:50

回答

9

您需要過濾以及排序數組。

保持你原來的代碼結構,你可以添加一個過濾器是這樣的:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
            initWithKey: @"price" ascending: YES]; 

NSArray *sortedArray = [self.displayItems sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortDescriptor]]; 

NSPredicate *pred = [NSPredicate predicateWithFormat: @"price < 100"]; 
NSMutableArray *filteredAndSortedArray = [sortedArray filteredArrayUsingPredicate: pred]; 

[self setDisplayItems: [filteredAndSortedArray mutableCopy]]; 

[self.tableView reloadData]; 

如果性能成爲一個問題,你可能要逆過濾和排序,但是這是一個細節。

0
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"your key" ascending:true]; 
[yourarray sortUsingDescriptors:[NSArray arrayWithObject:sorter]]; 
[sorter release]; 
+0

謝謝,但是我不是那樣的嗎?我不僅需要對價格(我的鑰匙)進行分類,而且如果它<= 100等,也只能顯示價格... – hanumanDev 2013-03-13 10:37:30

+0

爲什麼要降級? NSSortDescriptor僅用於對數組進行排序。如果您想設置價格的限制,請使用NSPredicate。 – Girish 2013-03-13 10:40:39

+0

Downvote,因爲你沒有回答這個問題。 – Sebastian 2013-03-13 10:42:18

1

可以先陣列具有指定範圍過濾在價格,則排序後的數組排序的過濾陣列&顯示在tableview中!!!

爲了濾除,您可以使用NSPredicate &進行排序,你可以使用相同的NSSortDescriptor

希望這可以幫助你!

0
NSMutableArray * weekDays = [[NSMutableArray alloc] initWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday", nil]; 
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
NSMutableArray *dictArray = [[NSMutableArray alloc] init]; 

for(int i = 0; i < [weekDays count]; i++) 
{ 
    dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%i",i],@"WeekDay",[weekDays objectAtIndex:i],@"Name",nil]; 
    [dictArray addObject:dict]; 
} 
NSLog(@"Before Sorting : %@",dictArray); 

@try 
{ 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:NO]; 
    NSArray *descriptor = @[sortDescriptor]; 
    NSArray *sortedArray = [dictArray sortedArrayUsingDescriptors:descriptor]; 
    NSLog(@"After Sorting : %@",sortedArray); 
} 
@catch (NSException *exception) 
{ 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorting cant be done because of some error" message:[NSString stringWithFormat:@"%@",exception] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
    [alert setTag:500]; 
    [alert show]; 
    [alert release]; 
} 
相關問題