【问题标题】:Match multiple strings in multiple NSArray匹配多个 NSArray 中的多个字符串
【发布时间】:2011-04-14 23:18:01
【问题描述】:

我需要通过将 XML 元素中的字符串与另一个 NSArray 中的字符串列表进行匹配来从 XML 的 NSArray 中选择故事

XML 包含故事,每个故事都有三个条件,比如“水果”、“蔬菜”、“香料”,每个条件都包含一个短语。示例故事可能如下所示:

<story>
    <title>I love cooking</title>
    <fruit>Oranges</fruit>
    <veg>Cauliflower</veg>
    <spice>Mixed spice</spice>
    <blurb>losts of text and stuff....</blurb>
</story>

我在从 pList 生成的 NSMutableDictionary 中有三个键/值对字典

<Fruit:dictionary>
    'Ripe bananas' : 1
    'Green bananas' : 0
<Veg:dictionary>
    'Green beans' : 1
    'Cauliflower' : 0
<Spice:dictionary>
    'Nutmeg' : 1
    'Mixed spice' : 0

我不知道钥匙是什么,我需要将故事中的标签与钥匙相匹配。

即故事水果标签:“成熟的香蕉”匹配水果键列表中的“成熟的香蕉”

我可以使用构建三个键数组

NSMutableDictionary *fruitTagsDict = [prefsDictionary objectForKey:@"Fruits"];
NSArray *fruitTags = [fruitTagsDict allKeys];

我通过故事 XML 循环提取标签

for (id myArrayElement in storyArray) {
    NSString *fruitString = [NSString stringWithString:[myArrayElement fruit]];
    //BOOL isTheObjectThere = [issueTags containsObject:fruitString];

    NSString *vegString = [NSString stringWithString:[myArrayElement veg]];

    NSString *spiceString = [NSString stringWithString:[myArrayElement spice]];

    //if ([[fruitTags objectAtIndex:row] isEqualToString:fruitString]) {
    //NSLog(@"Yo %@", fruitString);
            // ADD TO A NEW ARRAY OF MATCHING STORIES
    //}
        // Fails because row is undeclared
}

然后我开始上釉。

isTheObjectThere 行产生 nil 然后在循环结束时崩溃

我看过: Filter entire NSDictionaries out of NSArray based on multiple keys Making the Code check to see if the Text in a Text box matches any of the Strings in an NSArray

似乎谓词就是答案,但坦率地说,我感到困惑。

我需要在元代码中做什么

repeat with stories
    if storyFruitTag is in fruitTagArray 
    OR storyVegTag is in vegTagArray 
    OR storySpiceTag is in spiceTagArray
        Add to new array of matching stories

希望我已经解释得足够多以获得一些指示,我研究了 NSMutableSet 和 Intersect (Xcode: Compare two NSMutableArrays),但是太多信息的力量让我着迷

【问题讨论】:

    标签: iphone objective-c cocoa-touch nsarray predicate


    【解决方案1】:

    这里有一个使用关键路径判断是否匹配的简单方法:

     if ([prefsDict valueForKeyPath:[NSString stringWithFormat:@"Fruit.%@", storyFruitTag]] ||
         [prefsDict valueForKeyPath:[NSString stringWithFormat:@"Veg.%@", storyVegTag]] ||
         [prefsDict valueForKeyPath:[NSString stringWithFormat:@"Spice.%@", storySpiceTag]]) {
           // one of the story's tags matches a key in one of the corresponding dictionaries
       }
    

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2017-02-12
      • 1970-01-01
      • 2014-05-28
      相关资源
      最近更新 更多