Ios 如何构造具有多个复杂条件的NSPredicate

Ios 如何构造具有多个复杂条件的NSPredicate,ios,nspredicate,Ios,Nspredicate,考虑一个具有以下属性的CustomObject类: @property(nonatomic, strong) NSNumber *source; @property(nonatomic, strong) NSArray<CustomObject2> *linkedItems; @property(nonatomic, strong) NSString *parentId; 在使用谓词之后,我希望有对象1、2和5 我被一个优雅的解决方案难倒了。。。有什么想法吗?查找NSCompoun

考虑一个具有以下属性的
CustomObject
类:

@property(nonatomic, strong) NSNumber *source;
@property(nonatomic, strong) NSArray<CustomObject2> *linkedItems;
@property(nonatomic, strong) NSString *parentId;
在使用谓词之后,我希望有对象1、2和5


我被一个优雅的解决方案难倒了。。。有什么想法吗?

查找
NSCompoundPredicate
的文档,它的类方法可以使用其他谓词作为输入为
条件构造谓词。

查找
NSCompoundPredicate
的文档,它的类方法可以使用其他谓词作为输入,为
条件构造谓词。

这不就是按第一个谓词过滤吗?predicateB和predicateC在哪里发挥作用?是的,在上面的代码中,我只按一个谓词进行筛选,而按多个谓词进行筛选使用NSCompoundPredicate(类型:。和PredicateType,子谓词:[predicateA,predicateB,predicateC])@Zach I更新了答案以更好地反映问题。这不就是通过第一个谓词过滤吗?predicateB和predicateC在哪里发挥作用?是的,在上面的代码中,我只按一个谓词过滤,而按多个谓词过滤。使用NSCompoundPredicate(类型:。和PredicateType,子谓词:[predicateA,predicateB,predicateC])@Zach I更新了答案以更好地反映问题。
    //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)
    //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)