How to write a BOOL predicate in Core Data?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-17 15:24:58

问题


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?


回答1:


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.




回答2:


Swift 4.0

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



回答3:


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)




回答4:


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)




回答5:


Swift 4

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

Swift 3

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



回答6:


Swift 3.0 has made a slight change to this:

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


来源:https://stackoverflow.com/questions/6169121/how-to-write-a-bool-predicate-in-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!