BOOL to NSString
Solution 1
Use a ternary operator:
BOOl isKind= [thing isKindOfClass:[NSString class]];
NSLog(@"Is Kind of NSString: %d", isKind);
NSLog(@"Is Kind of NSString: %@", isKind ? @"YES" : @"NO");
Solution 2
In the background BOOL acts like an int type so you can use %i to test for a BOOL type’s value in NSLog:
BOOL a = YES;
BOOL b = NO;
NSLog(@"a is %i and b is %i", a, b);
// Output: a is 1 and b is 0
Solution 3
So, I know that this is really old, but I thought I might as well toss my solution into the ring. I do:
#define NSStringFromBOOL(aBOOL) ((aBOOL) ? @"YES" : @"NO")
NSLog(@"Is Kind of NSString: %@", NSStringFromBOOL([thing isKindOfClass: [NSString class]]);
I feel that this is more in line with some of Apple's to-string macros (NSStringFromClass
, NSStringFromRect
, NSStringFromSelector
, and so on), and generally pretty simple to use on-the-fly. Just be sure to put that macro somewhere globally accessible, or frequently imported!
Solution 4
You print a BOOL like this:
NSLog(@"The BOOL value is %s", theBoolValue ? "YES" : "NO");
Or, with the new @
notation, one could do:
NSLog(@"The BOOL value is %@", @(theBoolValue));
Solution 5
NSLog uses a simple printf-style invocation format its text, and your code example is missing the character sequence needed to embed an object.
This should work:
NSLog(@"Is Kind of NSString: %@", ([thing isKindOfClass:[NSString class]]) ? @"YES" : @"NO");
Craig
Updated on June 16, 2020Comments
-
Craig almost 4 years
If I have a method that returns a
BOOL
, how do I cast that to anNSString
so I can print it out in console?For example, I tried doing this, which isn't working:
NSLog(@"Is Kind of NSString:", ([thing isKindOfClass:[NSString class]]) ? @"YES" : @"NO");
But I really want to actually turn the return value into an NSString. I know it's a primitive data type, so I can't call methods on it. Do I have to create a string separately and then use the Bool as a parameter in a method on NSString?