Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out string constant with NSLog on iOS

I have a string constant defined like this:

#define kMyString @"This is my string text!";

Somewhere in the code I would like to print-out this piece of code with NSLog like that:

NSLog(@"This is it: %@",kMyString);

But get a build error: Expected expression.

I have already looked at the Apple's Format Specifiers but could not figured it out.

Can someone please explain it to me how to do this?

Thanks!

like image 227
Borut Tomazin Avatar asked Mar 08 '12 11:03

Borut Tomazin


People also ask

How do you print a boolean in Objective-C?

There is no format specifier to print boolean type using NSLog. One way to print boolean value is to convert it to a string. Another way to print boolean value is to cast it to integer, achieving a binary output (1=yes, 0=no).

What is NSString?

A static, plain-text Unicode string object which you use when you need reference semantics or other Foundation-specific behavior.

How do you print an object in Objective-C?

15.4. 4.2 The Print Command With Objective-C Also, an additional command has been added, print-object or po for short, which is meant to print the description of an object. However, this command may only work with certain Objective-C libraries that have a particular hook function, _NSPrintForDebugger , defined.


2 Answers

You should remove ; from the definition of kMyString:

#define kMyString @"This is my string text!"

The way you did it is equivalent to:

NSLog(@"This is it: %@", @"This is my string text!";);
like image 184
sch Avatar answered Oct 13 '22 22:10

sch


%@ is for objects. BOOL is not an object.
On the bases of data type %@ changes as follows

For Strings you use %@
For int  you use %i
For float you use %f
For double you use %lf
like image 32
Vaibhav Sharma Avatar answered Oct 13 '22 22:10

Vaibhav Sharma