sefirosu
sefirosu

Reputation: 2648

how to print out bool in objective c

I have set a bool value for key TCshow in my NSUserDefault, I want to run a nslog test whether the key is saved or not, and i m trying to printout the bool value. here is my code but it s not working, any suggestions?

- (IBAction)acceptAction:(id)sender {
//key store to nsuserdefault
self.storedKey = [[NSUserDefaults alloc] init];
[self.storedKey setBool:YES forKey:@"TCshow"];
//trying to print out yes or not, but not working...
NSLog(@"%@", [self.storedKey boolForKey:@"TCshow"]);

}

Upvotes: 20

Views: 25152

Answers (7)

crifan
crifan

Reputation: 14328

already answered in another post, copy to here:


  • Direct print bool to integer
BOOL curBool = FALSE;
NSLog(@"curBool=%d", curBool);

-> curBool=0

  • Convert bool to string
char* boolToStr(bool curBool){
    return curBool ? "True": "False";
}

BOOL curBool = FALSE;
NSLog(@"curBool=%s", boolToStr(curBool));

-> curBool=False

Upvotes: 0

user907729
user907729

Reputation:

you should use

NSLog(flag ? @"Yes" : @"No");

here flag is your BOOL.

Upvotes: 20

Hot Licks
Hot Licks

Reputation: 47699

NSLog(@"The value is %s", [self.storedKey boolForKey:@"TCshow"] ? "TRUE" : "FALSE");

Upvotes: 4

Paul.s
Paul.s

Reputation: 38728

Just for the sake of using the new syntax you could always box the bool so that is an object and can be printed with %@

NSLog(@"%@", @( [self.storedKey boolForKey:@"TCshow"] ));

Upvotes: 0

Prasad G
Prasad G

Reputation: 6718

if([self.storedKey boolForKey:@"TCshow"]){
NSLog(@"YES");
}
else{
NSLog(@"NO");

}

I think it will be helpful to you.

Upvotes: 0

Peter Warbo
Peter Warbo

Reputation: 11700

%@ is for objects. BOOL is not an object. You should use %d.

It will print out 0 for FALSE/NO and 1 for TRUE/YES.

Upvotes: 44

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

NSLog(@"%d", [self.storedKey boolForKey:@"TCshow"]);

Upvotes: 3

Related Questions