簡體   English   中英

使用NSDictionary從NSMutableArray獲取特定字符串

[英]Get a specific string from an NSMutableArray using NSDictionary

我正在學習iphone應用程序的開發和工作,可以讓你輸入兩個單詞並將它們組合起來。 將這兩個單詞和組合單詞輸入到字典中,然后將其存儲在可變數組中。 還有另一個選項允許您輸入整個單詞,如果它在數組中,它將返回兩個單獨的單詞。 我的問題是我不知道如何搜索數組並瀏覽每個對象並找出答案。 例如:

(
    {
    "Combined Word" = snowman;
    "Word 1" = snow;
    "Word 2" = man;
},
    {
    "Combined Word" = dirtbike;
    "Word 1" = dirt;
    "Word 2" = bike;
},
    {
    "Combined Word" = schoolbus;
    "Word 1" = school;
    "Word 2" = bus;
},
    {
    "Combined Word" = raindrop;
    "Word 1" = rain;
    "Word 2" = drop;
}

如果我輸入schoolbus並按下按鈕,我如何編碼以便搜索可變數組並分析每個對象的“組合字”,這樣輸入的單詞就是一個值,它將返回相應的“Word 1”和“字2“。

我不知道是否有更好或更有效的方法,但我可以嘗試這樣的事情:

NSString* word1;
NSString* word2;
for(NSDictionary *dict in yourArray){
   if([[dict objectForKey:@"Combined Word"] isEqualToString:yourSearchWord]]){
       word1 = [dict objectForKey:@"Word 1"];
       word2 = [dict objectForKey:@"Word 2"]; 
   }
}

請注意,這是一個拼寫錯誤,並沒有簽入XCode。

使用NSPredicate

NSString *value= @"value1";
NSPredicate *key1Predicate = [NSPredicate predicateWithFormat:@"%@ IN self.@allValues", value];
NSArray *filteretSet1 = [dataSet filteredArrayUsingPredicate:key1Predicate];
NSLog(@"filteretSet1: %@",filteretSet1);

希望這會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM