Zach
Zach

Reputation: 4069

How to construct NSPredicate with multiple complex conditions

Consider a CustomObject class that has the following properties:

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

How would I construct an NSPredicate to handle the following scenario:

  1. All CustomObject objects with source value of 1 and non-empty/non nil linkedItems array.
  2. All CustomObject objects with source value of 2 and parentId equal to item1.
  3. All other CustomObjects with source values other than 1 or 2

For example:

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

After using the predicate I would like to have Objects 1, 2, and 5.

I'm stumped on an elegant solution for this... any thoughts?

Upvotes: 0

Views: 134

Answers (2)

RLoniello
RLoniello

Reputation: 2329

    //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)

Upvotes: 0

Charles Srstka
Charles Srstka

Reputation: 17040

Look up the documentation for NSCompoundPredicate, which has class methods that can construct predicates for AND, OR, and NOT conditions using other predicates as input.

Upvotes: 2

Related Questions