How to write a BOOL predicate in Core Data?
I have an attribute of type BOOL
and I want to perform a search for all managed objects where this attribute is YES
.
For string attributes it is straightforward. I create a predicate like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName = %@", userName];
But how do I do this, if I have a bool attribute called selected and I want to make a predicate for this? Could I just do something like this?
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selected = %@", yesNumber];
Or do I need other format specifiers and just pass YES
?
From Predicate Programming Guide:
You specify and test for equality of Boolean values as illustrated in the following examples:
NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"anAttribute == %@", [NSNumber numberWithBool:aBool]];
NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == YES"];
You can also check out the Predicate Format String Syntax.
Swift 4.0
let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
Don't convert to NSNumber, nor use double "=="
More appropriate for Swift >= 4:
NSPredicate(format: "boolAttribute = %d", true)
Note: "true" in this example is a Bool (a Struct)
Swift 3
let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
In Swift 3 you should use NSNumber(value: true)
.
Using NSNumber(booleanLiteral: true)
and in general any literal initialiser directly is discouraged and for example SwiftLint (v. 0.16.1) will generate warning for usage ExpressibleBy...Literal
initialiser directly:
Compiler Protocol Init Violation: The initializers declared in compiler protocols such as
ExpressibleByArrayLiteral
shouldn't be called directly. (compiler_protocol_init)
Swift 4
request.predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
Swift 3
request.predicate = NSPredicate(format: "field = %@", value as CVarArg)