如何过滤NSDictionary以在Objective-C中显示特定关键字



我想实际检查字典中的内容,如果它有我需要的关键字并显示它。如果它没有我要查找的关键字,它就不会显示它。

例如,一本城市词典,每个城市都有该城市的描述。我想在该描述中查找关键字"mall",如果该城市有该关键字,它应该显示该城市及其描述。

我该怎么做?提前感谢!:)

我会循环浏览字典,并使用rangeOfString查找单词"mall"

    NSMutableArray *array = [NSMutableArray array];
    for (NSString *aKey in [dict allKeys]) {
        NSString *desc = [dict valueForKey:aKey];
        if ([desc rangeOfString:@"mall"].length == 4) {
            [array addObject:[NSDictionary dictionaryWithObject:desc forKey:aKey]];
        }
    }
    //do what you want with array to display the values

valueForKey方法。

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDictionary/valueForKey:

您可以创建一个if情况,如果它返回nil,则不显示任何内容。否则,显示返回的值。

下面是一个使用的例子

NSString *string = [NSString stringWithString:[dictionary valueForKey:@"mall"]]; if (string) //Send that string to somewhere where it would be visible ;

最新更新