I'm trying to dynamically create predicates and perform a fetch.
Values can either be String or Int, when and int value is sent to NSPredicate initializer it crashes with the following error:
-[__NSCFNumber rangeOfString:]: unrecognized selector sent to instance
I know the problem is %@ format for Int, but is there a way to make this dynamic so that I don't have to manually check for String and Int and then create the predicate?
var keyValues: [String: AnyObject]
var predicates: [NSPredicate]()
for (key, value) in keyValues {
var predicate = NSPredicate(format: "%K = %@", key: [value])
predicates.append(predicate)
}
var compundPredicate = NSCompoundPredicate.andPredicateWithSubpredicates(predicates)
value as NSObject
does the trick:
var keyValues: [String: AnyObject] = ["name" : "John Doe", "age" : 39]
var predicates = [NSPredicate]()
for (key, value) in keyValues {
var predicate = NSPredicate(format: "%K = %@", key, value as NSObject)
predicates.append(predicate)
}
var compundPredicate = NSCompoundPredicate.andPredicateWithSubpredicates(predicates)
println(compundPredicate)
Output:
name == "John Doe" AND age == 39
Update for Swift 3/4:
let keyValues = ["name" : "John Doe" as NSObject, "age" : 39 as NSObject]
var predicates = [NSPredicate]()
for (key, value) in keyValues {
let predicate = NSPredicate(format: "%K = %@", key, value)
predicates.append(predicate)
}
let compundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
Or shorter:
let keyValues = ["name" : "John Doe" as NSObject, "age" : 39 as NSObject]
let predicates = keyValues.map { NSPredicate(format: "%K = %@", $0.key, $0.value) }
let compundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With