Proper way to convert BOOL value into INT?
Everytime when I tried to convert BOOL value into int. INT value is showing -8 for True and 0 for False. Ideally it should return 1 for true.
I have tried all possible ways of conversion like
int val=Info.isattachementDownloadable;
int val=[[NSString stringWithFormat:@"%d", Info.isattachementDownloadable] intValue];
int val=(int)Info.isattachementDownloadable;
where Info.isattachementDownloadable
return BOOL
In all ways its showing -8开发者_如何学Go for TRUE.
Any suggestion ?
Maybe that will help(thought i don't know why it may be needed in the first place)
NSInteger i = @(YES).integerValue;
Hope that it helps you.
It is much quicker to do it like this:
BOOL myBool = YES;
int myInt = (myBool ? 1 : 0);
myInt
will be 1 if myBool
is YES, and 0 if myBool
is NO.
It is always possible to use the object-oriented wrapper around numeric primitives (e.g. C's int). So am I answering the question? both yes and no depending on your viewpoint. However, here is what I prefer to use when using BOOL as input:
NSNumber *numval = [NSNumber numberWithBool:Info.isattachementDownloadable];
And if you really need to use the primitive datatype:
int val = [numval intValue];
BOOL myBool;
int myInt;
if (myBool) myInt = 1;
else myInt = 0;
You can just assign BOOL value to int since YES and NO are just shortcuts for 1 and 0. You can also perform maths operations on BOOLs. FYI, BOOLs can even hold values from -128 up to 127 since they are just typedefs for signed chars.
BOOL someBool = YES;
int intFromBool = someBool;
NSLog(@"%d", intFromBool);
intFromBool -= YES;
NSLog(@"%d", intFromBool);
Reference: https://www.bignerdranch.com/blog/bools-sharp-corners/
精彩评论