How to write a BOOL predicate in Core Data?

我怕爱的太早我们不能终老 提交于 2019-11-27 18:04:20

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

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)

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 4

request.predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))

Swift 3

request.predicate = NSPredicate(format: "field = %@", value as CVarArg)

Swift 3.0 has made a slight change to this:

let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(booleanLiteral: true))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!