【问题标题】:Use NSPredicates/KVC to grab an array of sibling keys使用 NSPredicates/KVC 获取兄弟键数组
【发布时间】:2010-12-22 18:53:48
【问题描述】:

另一种说法可能是......

NSPredicate "state.country == 'United States'"

就像

SQL "Select * from state where state.country = 'United States'

那么我该如何做这个谓词呢?

SQL "Select state.name from state where state.county = 'United States'"

原帖:

我有一个字典数组,如下所示:

lists
  states
    state
    country
  country
    country

我有按国家/地区过滤状态的代码。不过,我敢打赌有一种更清洁的方法。

NSArray *states = [lists valueForKey:@"states"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryname == %@", selectedCountry];
states = [states filteredArrayUsingPredicate:predicate];
states = [states valueForKeyPath:@"state"];

想法?

【问题讨论】:

  • 我可能遗漏了一些明显的东西,但你的结构图对我来说绝对没有意义。能举个具体的例子吗?
  • 他想获取给定国家名称的状态。他搜索库比蒂诺并得到加利福尼亚,对吗?
  • 是的。州有一个名称和一个国家字符串。获取具有 state.country == "United States" 的州列表。 State 类有 state.state、state.country。

标签: iphone cocoa ios nspredicate key-value-coding


【解决方案1】:

你几乎明白了:

NSDictionary * lists = ...;

这是你原来的词典

NSArray *states = [lists objectForKey:@"states"];

这是从字典中检索状态数组。大概这些是实际的“状态”对象(即,您创建了一个名为 State 的类)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryname == %@", selectedCountry];

这将创建一个谓词,它将-[State countryname] 的结果与selectedCountry 变量引用的值进行比较。或者,如果states 数组包含字典,这会将-[NSDictionary objectForKey:@"countryname"] 的结果与selectedCountry 引用的值进行比较。

states = [states filteredArrayUsingPredicate:predicate];

这将从[[aState countryname] isEqual:selectedCountry]所在的数组中检索所有状态

states = [states valueForKeyPath:@"name"];

这将创建一个包含每个州名称的新数组。这个新数组的顺序将与您过滤的 states 数组的顺序相同。

【讨论】:

  • 看起来这是最干净的方式。
【解决方案2】:

我只使用 NSArray 而不是 NSDictionary,所以我不知道这有多大用处,但我正在使用它:

matchingTour = [self.tours filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"tourCode == %@", tourCode]];

其中 self.tours 是 Tour 对象的 NSArray。 Tour 对象具有 NSString *tourCode 的属性。 matchingTour 是 NSArray 类型。

当我读到这篇文章时,我很惊讶,尝试了它,它第一次工作,我得到了一个只包含一个旅游的数组!

在您的“树”中,您没有显示任何属性名称“国家名称”——只是想知道。

【讨论】:

    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多