2013-10-08 25 views
-1

我的字典查找ArrayOfDictionaries詞典與特定鍵值對

for(int i = 0; i < 5; i++) { 
    NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionary]; 

    [_myDictionary setObject:[NSString stringWithFormat:@"%d",i] forKey:@"id"]; 
    [_myDictionary setObject:label.text @"Name"]; 
    [_myDictionary setObject:label1.text @"Contact"]; 
    [_myDictionary setObject:label2.text @"Gender"]; 
} 

[_myArray addObject:_myDictionary]; 

現在我要挑一本字典從其objectForKey數組的數組:@「標識」爲1或2或別的東西,像有一個SQL查詢從表其中id = 2 我知道這個過程

int index = [_myArray count]; 

for(int i = 0; i < 5; i++) 
{ 

NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionaryWithDictionary:[_myArray objectAtIndex:i]]; 

if([[_myDictionary objectForKey:@"id"] isEqualToString:id]) 
{ 

index = i; 

return; 

} 

} 

if(index != [_myArray count]) 
    NSLog(@"index found - %i",index); 

else 
    NSLog(@"index not found"); 

任何幫助,將不勝感激選擇*。 在此先感謝!

+3

什麼是你的實際問題? – occulus

回答

2

試試這個,這是通過使用快速列舉

NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
    for(dict in _myArray) 
    { 

     if([[dict valueForKey:@"id"] isEqualToString:@"1"]) 
     { 
      return; 
     } 
    } 
+0

這確實很快,但如果數組ID太長,包含帶有100個鍵的字典,則需要很長時間。沒有任何SQL類型的查詢。 – Swati

+1

它不會花費太多時間,您可以添加100個對象,僅用於測試目的,這是一個快速過程。 –

0

您應該使用[NSNumber numberWithInteger: i]而不是NSString。

代碼脫穎而出此搜索應該是這樣的:

NSString *valueToFind = [NSString stringWithFormat:@"%d", intValue]; // [NSNumber numberWithInteger: intValue] 
NSInteger index = [_myArray indexOfObjectPassingTest:^BOOL(NSDictionary *obj, NSUInteger idx, BOOL *stop) { 
    return [valueToFind isEqualToString: [obj objectForKey: @"id"]]; 
}]; 
NSDitionary *found = [_myArray objectAtIndex: index]; 
+0

你應該使用[NSNumber numberWithInteger:i]不是NSString。 – Swati

+0

在數組和字典中放入基本類型的正確方法是使用'NSNumber',轉換爲'NSString'可能會有問題(這取決於你在做什麼)。 –