NSPredicate with multiple arguments and “AND behaviour”

后端 未结 4 1503
夕颜
夕颜 2020-12-19 02:51

I have a function which fetches those objects from a particular entity that fulfill a specified criterion:

func fetchWithPredicate(entityName: String, argume         


        
4条回答
  •  天涯浪人
    2020-12-19 03:24

    To create a predicate (with a variable number of expressions) dynamically, use NSCompoundPredicate, e.g.

    let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates)
    

    where subPredicates is a [NSPredicate] array, and each subpredicate is created from the provided arguments in a loop with

    NSPredicate(format: "%K == %@", key, value)
    

    Something like this (untested):

    func fetchWithPredicate(entityName: String, argumentArray: [NSObject])  -> [NSManagedObject]  {
    
        var subPredicates : [NSPredicate] = []
        for i in 0.stride(to: argumentArray.count, by: 2) {
            let key = argumentArray[i]
            let value = argumentArray[i+1]
            let subPredicate = NSPredicate(format: "%K == %@", key, value)
            subPredicates.append(subPredicate)
        }
    
        let fetchRequest = NSFetchRequest(entityName: entityName)
        fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates)
    
        // ...
    }
    

提交回复
热议问题