如何构建具有多种复杂条件的NSPredicate

时间:2017-12-15 04:05:48

标签: ios nspredicate

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

@property(nonatomic, strong) NSNumber *source;
@property(nonatomic, strong) NSArray<CustomObject2> *linkedItems;
@property(nonatomic, strong) NSString *parentId;

如何构建NSPredicate来处理以下场景:

  1. 所有CustomObjectsource值为1且非空/非零linkedItems数组的对象。
  2. 所有CustomObjectsource值为2parentId等于item1的对象。
  3. CustomObjectssource
  4. 以外的所有其他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。

    我为这个问题难以理解......有什么想法吗?

2 个答案:

答案 0 :(得分:2)

查找NSCompoundPredicate的文档,其中包含的类方法可以使用其他谓词作为输入构建ANDORNOT条件的谓词。

答案 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)