【问题标题】:NSPredicate to filter Custom objects based on its property from Nested structureNSPredicate 根据嵌套结构中的属性过滤自定义对象
【发布时间】:2015-03-25 07:20:28
【问题描述】:

我正在尝试使用 NSPredicate 从下面显示的结构中过滤所有 CustomObjects,并为其属性“isSelected”设置值为 true。 我有一个嵌套结构,例如:isSelectedProperty-Object-NSArray-NSDictionary-NSArray

[
  {
    "title": "ABC",
    "list": [
      <CustomObject>.isSelected = true,
      <CustomObject>.isSelected = true,
      <CustomObject>.isSelected = true
    ]
  },
  {
    "title": "ABC",
    "list": [
      <CustomObject>.isSelected = false,
      <CustomObject>.isSelected = true,
      <CustomObject>.isSelected = true
    ]
  },
  {
    "title": "ABC",
    "list": [
      <CustomObject>.isSelected = false,
      <CustomObject>.isSelected = true,
      <CustomObject>.isSelected = true
    ]
  }
]

从这样的嵌套结构中,我需要过滤所有具有 isSelected = trueCustomObject 。所以我的问题是,

  • 是否可以使用 NSPredicate?
  • 是的,那么过滤这个结构的谓词语句会是什么?

请提供一些理解,以便我们了解如何实际处理此类结构。

编辑 - 非常接近解决方案

在谷歌搜索和 Muhammad Waqas 的回答的帮助下,我成功地使用

过滤了数组,如下所示
NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"list.isSelected CONTAINS[c] %@",@true];
NSArray *aArray = [mutArrContacts filteredArrayUsingPredicate:aPredicate];
NSArray *UnWrapped = [aArray valueForKey:@"list"];



<__NSArrayI 0x7fc969cde360>(
<__NSArrayM 0x7fc969f54a10>(
<ContactData: 0x7fc969f7a590>,
<ContactData: 0x7fc969f8dee0>
)
,
<__NSArrayM 0x7fc969f736f0>(
<ContactData: 0x7fc969f68310>
)
,
<__NSArrayM 0x7fc969f737a0>(
<ContactData: 0x7fc969f70340>
)
,
<__NSArrayM 0x7fc969f87430>(
<ContactData: 0x7fc969f65170>
)
,
<__NSArrayM 0x7fc969f874d0>(
<ContactData: 0x7fc969f51690>
)

)

但现在我正在努力将这些对象过滤成单个数组,例如

(
<ContactData: 0x7fc969f7a590>,
<ContactData: 0x7fc969f8dee0>,
<ContactData: 0x7fc969f68310>,
<ContactData: 0x7fc969f70340>,
<ContactData: 0x7fc969f65170>,
<ContactData: 0x7fc969f51690>
)

【问题讨论】:

    标签: ios objective-c cocoa nspredicate


    【解决方案1】:

    是的,您可以像这样使用 NSPredicate 过滤自定义对象

    NSPredicate *predicate = [NSPredicate    predicateWithFormat:@"ANY list.isSelected = %@",@true];
    NSArray *filteredArry=[[json filteredArrayUsingPredicate:predicate] copy];
    

    希望这会对您有所帮助。

    【讨论】:

    • 这是崩溃的。 Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[&lt;ContactData 0x7ff74ea48320&gt; valueForUndefinedKey:]: this class is not key value coding-compliant for the key ContactData.' 这里的 ContactData 是 NSObject 的子类,在 MyQuestion 中被称为 CustomObject。
    • 使用NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"list.isSelected CONTAINS[c] %@",@true]; 我能够得到过滤数组,但它是多维的,但我试图在单数组中得到它。明白我的意思了吗?
    • 要获得一个单维数组,您必须遍历每个元素并将其添加到您的新数组中......您无法使用 nspredicate 实现此目的
    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    相关资源
    最近更新 更多