Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why "format specifies type id but the argument has type int" crash

NSLog(@"%@",2);

Warning:format specifies type id but the argument has type int

Output enter image description here

Xcode shows a warning, but at runtime, why this code causes crash? thanks!

like image 984
ylovesy Avatar asked May 31 '16 09:05

ylovesy


1 Answers

id is a pointer to an Objective-C object. Ex. NSString * or NSDate *. So when you use %@, the compiler is expecting a pointer to the memory address where an object is stored.

An int is a "primitive" value type. It is not an object. It is an actual value stored in memory and is passed directly to the argument in NSLog statement.

The reason it is crashing is because you are passing a value of 2 to a placeholder that is looking for a pointer to a memory address. That's what "bad access" means. The %@ can't find anything because you haven't provided an accurate memory address pointer.

The fix here is to use

NSLog(@"%d",2);
like image 93
Mike Critchley Avatar answered Nov 11 '22 12:11

Mike Critchley