NSPredicate with boolean is not comparing a boolean to NO

自作多情 提交于 2019-12-19 12:38:13

问题


I'm using CoreData and my entity has a boolean property called "isReward".

I'm trying to fetch the entity and filter out all results where isReward == YES.

isReward != YES does not work.

isReward == NO does not work.

NSPredicate predicateWithFormat:"isReward != %@", [NSNumber numberWithBool:YES]] does not work

isReward == Nil works.

What gives?


回答1:


I'm guessing you'll want:

[NSPredicate predicateWithFormat:@"isReward = NO OR isReward = nil"]

(Per the Apple docs here, direct comparison to NO should be valid.)

In general, when comparing to null/nil in data terms, null == false evaluates to false and null != false evaluates false. Comparison to null generally evaluates to false, except when testing for IS NULL.

I would also say that indexing in general gives you better results when you search for equality, not inequality. This is fairly simple to refactor to in your case (though I'm not sure that it will matter to Core Data in general).

Also, if you would like it to always be YES or NO (and skip the check for nil), you need to explicitly set the default to NO.

However, you may have some semantic value in leaving it nil until it is explicitly set by your application. This is really up to what you're trying to do.



来源:https://stackoverflow.com/questions/7209941/nspredicate-with-boolean-is-not-comparing-a-boolean-to-no

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