考虑具有以下属性的CustomObject
类:
@property(nonatomic, strong) NSNumber *source;
@property(nonatomic, strong) NSArray<CustomObject2> *linkedItems;
@property(nonatomic, strong) NSString *parentId;
如何构建NSPredicate
来处理以下场景:
CustomObject
个source
值为1
且非空/非零linkedItems
数组的对象。CustomObject
个source
值为2
且parentId
等于item1
的对象。CustomObjects
或source
1
2
个值
醇>
例如:
Custom Object 1
source = 1
linkedItems = Custom Object2 1, CustomObject2 2
parentId = nil
Custom Object 2
source = 1
linkedItems = nil
parentId = nil
Custom Object 3
source = 2
linkedItems = nil
parentId = item1
Custom Object 4
source = 2
linkedItems = nil
parentId = item2
Custom Object 5
source = 3
linkedItems = Custom Object2 3
parentId = nil
使用谓词后,我希望有对象1,2和5。
我为这个问题难以理解......有什么想法吗?
答案 0 :(得分:2)
查找NSCompoundPredicate
的文档,其中包含的类方法可以使用其他谓词作为输入构建AND
,OR
和NOT
条件的谓词。
答案 1 :(得分:0)
//All CustomObject objects with source value of 1 and non-empty/non nil linkedItemsarray.
let predicateA = NSPredicate(format: "(source == 1) AND (linkedItems != nil) AND (linkedItems.isEmpty == false)")
//All CustomObject objects with source value of 2 and parentId equal to item1.
let predicateB = NSPredicate(format: "(source == 2) AND (parentId != %@"), item1)
//All other CustomObjects with source values other than 1 or 2
let predicateC = NSPredicate(format: "(source != 1) AND (source != 2)")
let predicate = NSCompoundPredicate(type: .AndPredicateType, subpredicates: [predicateA,predicateB,predicateC])
let filtered = yourArray.filteredArrayUsingPredicate(predicate)