【问题标题】:how to create a predicate that accesses to an object property inside an Array如何创建访问数组内对象属性的谓词
【发布时间】:2019-03-30 08:26:04
【问题描述】:

假设我有一个 Person 对象的 NSArray,它们由 2 个属性(名称和年龄)组成。 只是为了理解它是如何工作和实践的,我想知道如何创建一个谓词来访问数组的每个成员并过滤所有年龄属性大于或等于 30 的对象。 我就是想不通:

  NSPredicate *predicate = [NSPredicate predicateWithFormat:@">= 30"];

    [persons filteredArrayUsingPredicate:predicate];
    NSLog(@"%@",persons)

我应该在 predicateWithFormat 上输入什么? 提前谢谢!

【问题讨论】:

标签: objective-c predicate


【解决方案1】:

两个问题:

  1. 谓词格式为key - operator - value 例如

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age >= 30"];
    

    或使用占位符

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K >= %ld", @"age", 30];
    
  2. filteredArrayUsingPredicate 返回一个新数组

    NSArray *filteredArray = [persons filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", filteredArray)
    

更多信息请阅读Predicate Format String Syntax

【讨论】:

  • 非常感谢您的解决方案和建议!我现在的问题是我实际上不知道在 predicateWithFormat: 上放置什么来指定属性“age”它位于数组中的对象内。你有什么建议吗?
  • NVM 看起来它会自动为我执行并搜索具有“年龄”属性的成员,但是这到底是怎么回事呢?
  • persons 是什么类型?如果persons(更好的people)是字典或自定义类,代码应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
相关资源
最近更新 更多