Core Data and Booleans: Newbie Edition
UPDATE!
As pointed out by Jeff LaMarche and Julio Barros, there is an easier way to deal with Booleans in Core Data, and it is using Wolf Rentzsch‘s http://rentzsch.github.com/mogenerator/
Original Post:
There are a couple of things that I had trouble with while using a boolean with Core Data. The first was how to update this attribute, and the second was how to properly test against it.
I have an attribute in one of my Core Data entities that is of type Bool in my .xcdatamodel called isDone.
When I first tried to update the value to YES, I tried to do this:
![]()
This, quite rightly, gives the warning: “makes pointer from integer without a cast.” That is because Core Data does not support a boolean type. It will create your bool attribute with a type of NSNumber, which I could see when I looked at the header file for my item:
So the correct thing to do was save the NSNumber value of NO or YES (0 or 1) by using numberWithBool:
![]()
The second wrinkle was when I tried to test the value of this attribute. I first wrote:
The problem? This was always returning true! Because it was testing, basically, whether or not the NSNumber stored in the isDone property was nil or not. Even if its value was 0, if (item.isDone) evaluated to true.
What I did instead? Test against the boolValue
Hurray! And now I can get on with it!
-
Jeff LaMarche
-
http://www.e-string.com Julio Barros
-
am
-
http://eschatologist.net/blog/ Chris Hanson
-
am
-
Dalmazio

follow me on twitter