Reputation: 270733
I just created a Core Data data model and added some entities. Now I'm generating NSManagedObject
subclasses.
In the generated code, I found that one of my properties, whose type is "Boolean" in the data model, has turned into a property of type NSNumber
!
That's not correct, I thought. An NSNumber
is certainly not a boolean. Why doesn't it just use the Bool
type?
Then I thought that this might be another one of those annoying things of Objective-C. I think that just like Int
and Double
, a Bool
cannot be saved into Core Data so it has to use an NSNumber
. Am I right?
How to convert this NSNumber
to a Bool
and how to convert a Bool
to an NSNumber
? Maybe 0 = false and 1 = true? What about other values? This isn't type-safe at all...
Upvotes: 0
Views: 312
Reputation: 8402
for your question How to convert this NSNumber to a Bool and how to convert a Bool to an NSNumber?
u can do like below, for NSNumber
objects
//convert bool to number
NSNumber *boolInNumber = [NSNumber numberWithBool:YES]; //or NO
//get back, convert number to bool
NSNumber *aNum = [NSNumber numberWithBool:YES]; //get the NSNumber instance
BOOL numberInBool = [aNum boolValue];
and aslo u can convert to other types, for more info check the class reference hear
sorry for the delay, and for swift version,
var numInBool:NSNumber? //is a nsnumber instance
numInBool = NSNumber(bool: true) //get number from bool (number in bool)
var boolInNum:Bool? //it is boolean
boolInNum = numInBool!.boolValue //get bool from number (bool from number)
yes you are right... :) as per @fred doc said,
let numInBool = NSNumber(bool: true)
let boolInNum = numInBool.boolValue
Upvotes: 1