2012-12-24 33 views
3

我有一個NSMutableArray的是這樣的:Objective C:用字典鍵的值過濾掉NSMutableArray的結果?

(
     { 
     City = "Orlando"; 
     Name = "Shoreline Dental"; 
     State = Florida; 
    }, 
     { 
     City = "Alabaster "; 
     Name = Oxford Multispeciality; 
     State = Alabama; 
    }, 
     { 
     City = Dallas; 
     Name = "Williams Spa"; 
     State = Texas; 
    }, 
     { 
     City = "Orlando "; 
     Name = "Roast Street"; 
     State = Florida; 
    } 
) 

現在我該怎麼解決這NSMutableArray中獲得相應於國家「佛羅里達」 我希望得到

(
     { 
     City = "Orlando"; 
     Name = "Shoreline Dental"; 
     State = Florida; 
    }, 
{ 
     City = "Orlando "; 
     Name = "Roast Street"; 
     State = Florida; 
    } 
) 

我去這個代碼的結果,但它再次顯示前四個字典。

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Florida" ascending:YES]; 
     NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor]; 
     NSArray * sortedArray = [arr sortedArrayUsingDescriptors:descriptors]; 
+0

你真的不想排序數組,但檢索一個子數組,對吧? – 2012-12-24 07:56:56

+0

是的,你對.. – Honey

+0

是城市,名稱,州是一個對象的屬性?或直接在數組中? –

回答

6

嘗試使用比較器模塊:

NSIndexSet *indices = [array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { 
    return [[obj objectForKey:@"State"] isEqualToString:@"Florida"]; 
}]; 
NSArray *filtered = [array objectsAtIndexes:indices]; 

或者,你可以使用一個謂語,以及:

NSPredicate *p = [NSPredicate predicateWithFormat:@"State = %@", @"Florida"]; 
NSArray *filtered = [array filteredArrayUsingPredicate:p]; 
+0

替代答案不工作,我無法找到錯誤:( –

+0

@AnoopVaidya查看更新。 – 2012-12-24 08:23:53

+0

是的,現在它的工作:) –

2

如果陣列包含字典那麼你可以使用NSPredicate過濾掉你的陣列如下:

NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"State CONTAINS[cd] Florida"]; 
theFilteredArray = [theArray filteredArrayUsingPredicate:thePredicate]; 
1

假設你的數組名稱是:arr

的發現的典型方式這一個,雖然有點過時的方式....

for (NSDictionary *dict in arr) { 
    if ([[dict objectForKey:@"State"]isEqualToString:@"Florida"]) { 
     [filteredArray addObject:dict]; 
    } 
} 
NSLog(@"filteredArray->%@",filteredArray); 

使用謂詞和塊已經發布:)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"State = %@", @"Florida"]; 
NSArray *filteredArray = [arr filteredArrayUsingPredicate:predicate]; 
NSLog(@"filtered ->%@",filteredArray);