-2

(XCode 4.3) Why does the following crash at the NSLog statement with EXC_BAD_ACCESS?

BOOL autoFlag
@property BOOL autoFlag
@synthesize autoFlag

[object setAutoFlag:YES]

NSLog(@"%@", [object autoFlag]);  //crashes here in debugger with EXC_BAD_ACCESS

I managed to get around it with NSLog(@"%d"..., which prints 1, but why doesn't @"%@" work? I thought it just converts the value to a string?

raffian
  • 31,267
  • 26
  • 103
  • 174
  • 5
    `%@` is used to print an object. A BOOL value is not an object. – Hot Licks Jun 19 '12 at 00:29
  • Makes sense, but is there a format identifier for printing scalar values as strings, regardless of type? PS: You should post as an answer instead of a comment, I'd accept it. – raffian Jun 19 '12 at 00:33
  • 2
    `NSLog(@"%s", flag ? "YES" : "NO");` -- Basic C stuff. – Hot Licks Jun 19 '12 at 01:11
  • If you had researched the question you'd know that `%@` is for printing an object, and that a BOOL is not an object. – Hot Licks Jun 19 '12 at 02:34

2 Answers2

6

%@ is used to print the description of objects that are descendants of the NSObject class, this however can be overwritten to make your objects print whatever you want.

Unless autoFlag is an object it will crash your program. It is very common to get these type of errors in NSLog Statements since the compiler cant tell what kind of "thing" you want to print and most of the time it wont be able to know before hand (there are some exceptions in where it will tell you that you are using the wrong identifier).

If what you want to see is something like "True" or "YES" then you need something like

NSLog(@"Auto Flag: %@",object.autoFlag? @"True":@"False");
Erik B
  • 40,889
  • 25
  • 119
  • 135
Pochi
  • 13,391
  • 3
  • 64
  • 104
2

Take a look at: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

%d works because you are telling it to print your boolean value as an integer, so you will get back either 0 (false) or 1 (true) using this method. There is no specific formatter for a boolean.

You encountered a crash because the code is expecting a pointer to a memory address by using %@, and instead you gave it a primitive datatype, in this case a boolean. When the application tried to use this address and there was no object there, you got a EXEC_BAD_ACCESS.

gdavis
  • 2,556
  • 1
  • 20
  • 25