如何在核心数据中编写 BOOL 谓词?

我有一个类型为 BOOL的属性,我希望搜索该属性为 YES的所有托管对象。

对于字符串属性,它非常简单:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName = %@", userName];

但是,如果我有一个名为 选定的 bool 属性,并且我想为它做一个谓词,那么我该如何做呢?我能做这样的事吗?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selected = %@", yesNumber];

或者我需要其他格式说明符,只是通过 YES

48459 次浏览

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

Swift 3.0 has made a slight change to this:

let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(booleanLiteral: true))

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)

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)

if you do not want to hard-code the attribute name inside the format you can use #keyPath with something like,

let samplePredicate = NSPredicate(format: "%K != %d", #keyPath(Foo.attr), true)