2012-11-25 14 views
1

我有一個包含2個對象的數組。每個對象都有一個「類型」鍵。該關鍵的價值之一是「資源」,另一個是「作物」。使用NSSortDescriptor沒有得到正確的排序

我想排序通過該數組,並創建一個新的數組,只包含我需要的類型的對象。我認爲這段代碼做到了......

-(NSArray*)getItemsOfType:(NSString *) type 
{ 
    NSSortDescriptor *sortDescriptor; 
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:type 
               ascending:YES]; 
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
    NSArray *sortedArray; 
    sortedArray = [templateObjects sortedArrayUsingDescriptors:sortDescriptors]; 

    return sortedArray; 
} 

但是,它似乎只是將當前數組排序爲某種順序。我如何改變這個功能來做我需要的?所以我需要使用「initWithKey:升序:選擇器:」?

UPDATE

我只是想上面的代碼上面這段代碼...

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"templateObjects.type like %@", type]; 

    NSArray *newArray = [templateObjects filteredArrayUsingPredicate:predicate]; 

但newArray只是看起來是空的?我有一種感覺@「templateObjects.type」部分是錯誤的?

更新2

確定這些代碼做什麼,我需要它..

-(NSArray*)getItemsOfType:(NSString *) type 
{ 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type CONTAINS[cd] %@", type]; 

    NSArray *newArray = [templateObjects filteredArrayUsingPredicate:predicate]; 

    NSSortDescriptor *sortDescriptor; 
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:type 
               ascending:YES]; 
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
    NSArray *sortedArray; 
    sortedArray = [newArray sortedArrayUsingDescriptors:sortDescriptors]; 

    return sortedArray; 
} 
+1

你需要過濾('filteredArrayUsingPredicate:')然後排序。 – rmaddy

+0

所以我會做類似「NSPredicate * predicate = [NSPredicate predicateWithFormat: @」templateObjects.type like%@「,type]; [array filterUsingPredicate:predicate];」 ? – Phil

+0

對「filteredArrayUsingPredicate:」的調用返回一個只包含匹配對象的新數組。然後根據需要對新數組進行排序。 – rmaddy

回答

0

使用

[NSPredicate predicateWithFormat: @"type like %@", type]; 

,而不是

[NSPredicate predicateWithFormat: @"templateObjects.type like %@", type]; 

所以

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"type like %@", type]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"type CONTAINS[cd] %@", type]; 

像你說的兩個對象類型鍵這將工作。