I want to convert integers 0
and 1
to BOOLEAN YES
and NO
My code:
NSNumber *num = 0;
BOOL myBool = [num boolValue];
NSLog(@"bool is: %@",myBool);
It gives output as (null)
What could be wrong?
First of all, the initialization of your NSNumber
is incorrect. You should use one of the +numberWith:
class methods defined on NSNumber
:
+ (NSNumber *)numberWithChar:(char)value;
+ (NSNumber *)numberWithUnsignedChar:(unsigned char)value;
+ (NSNumber *)numberWithShort:(short)value;
+ (NSNumber *)numberWithUnsignedShort:(unsigned short)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithUnsignedInt:(unsigned int)value;
+ (NSNumber *)numberWithLong:(long)value;
+ (NSNumber *)numberWithUnsignedLong:(unsigned long)value;
+ (NSNumber *)numberWithLongLong:(long long)value;
+ (NSNumber *)numberWithUnsignedLongLong:(unsigned long long)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithDouble:(double)value;
+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithInteger:(NSInteger)value NS_AVAILABLE(10_5, 2_0);
+ (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value NS_AVAILABLE(10_5, 2_0);
BOOL
s are just signed char
s, so you cannot use the %@
format specifier, but you can use any of the integral format specifiers such as %d
, %i
or %c
.
However, to output YES
or NO
, you'd need to use a string:
NSLog(@"bool is: %@", (myBool) ? @"YES" : @"NO");
Given the incorrect assignment to NSNumber
did you really mean to create an object containing an integer, or is your title question "convert int to BOOL" correct?
If the latter then to convert an int
with the value 0
or 1
to BOOL
you just cast:
int num = ...; // num is 0 or 1
BOOL myBool = (BOOL)num; // myBool is NO or YES
However a better conversion is:
BOOL myBool = num != 0; // myBool is NO for 0, YES for anything else
as this follows the Obj-C (and C) notion that zero is false and non-zero true.
If you wish to convert a BOOL
value to the strings "YES"
and "NO"
then this simple function will do it efficiently:
NS_INLINE NSString *BoolToStr(BOOL b) { return b ? @"YES" : @"NO"; }
just place it in a convenient header and import wherever you need it.
To Covert Int
to BOOL
convert an int with the value 0 or 1 to BOOL you just cast
NSNumber *num = [NSNumber numberWithInt:0]; // num is 0 or 1
BOOL myBool = [num boolValue]; // myBool is NO or YES
As sch mentioned you messed it up right here:
NSNumber *num = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With