CaffeineShots
CaffeineShots

Reputation: 2162

AND and OR combined with NSPredicate. IOS Swift

A dynamic or predicate for my coredata get query

    var predicate = [NSPredicate]()
    //this three is or
        predicate.append(NSPredicate(format: "item_parent_id = %i", 1))
        predicate.append(NSPredicate(format: "item_parent_id = %i", 3))       
        predicate.append(NSPredicate(format: "item_parent_id = %i", 5))

    // but this one is and
        predicate.append(NSPredicate(format: "price_date CONTAINS[cd] %@", 'timestamp'))

    var compound = NSCompoundPredicate.orPredicateWithSubpredicates(predicate)

the first three constraint is for OR operator and the last constraint for date is AND

I spent quite time for this, I am new in swift development and I'm not used to Objective C , that is why I'm having a hard time translating to swift what I found written in objective c.

if possible write the answer in swift , any comment and suggestion would be a big help. THanks in advance

obj c - source #1
obj c - source #2

Upvotes: 3

Views: 733

Answers (1)

rickster
rickster

Reputation: 126117

If you're looking for an operation like (a OR b OR c) AND d, you need two compound predicates:

var orList = [NSPredicate]()
//this three is or
orList.append(NSPredicate(format: "item_parent_id = %i", 1))
orList.append(NSPredicate(format: "item_parent_id = %i", 3))       
orList.append(NSPredicate(format: "item_parent_id = %i", 5))
let orPredicate = NSCompoundPredicate.orPredicateWithSubpredicates(orList)

// but this one is and
let other = NSPredicate(format: "price_date CONTAINS[cd] %@", 'timestamp')

let compound = NSCompoundPredicate.andPredicateWithSubpredicates([orPredicate, other])

Upvotes: 8

Related Questions