views:

729

answers:

3

Does anyone know of an easy way to add a single backslash "\" to a NSString in Objective-C? I am trying to have a NSString *temp = @"\/Date(100034234)\/";

I am able to get a double backslash or no backslash, but unable to get a single backslash. Any help would be appreciated. Thanks

+2  A: 

The string @"\\" is a single backslash, @"\\\\" is a double backslash

cobbal
Are you sure about it? When I print the NSString using NSLog it shows up as a double backslash.
Using NSLog(string) is bad practice; all someone has to do to crash your system is pass in e.g. %d, and it'll be interpreted as a dereference for a value. If you want to print out the value of an NSString on its own, then you should use:NSLog(@"@%",string)since then no values in the 'string' will affect the resulting output, which is an object type.
AlBlue
+1  A: 

This is a bug in NSLog. I found a mailing list archive with a message dated in 2002 of someone that filed a bug for this here. The person also said this:

Nothing has been done as far as I can tell. I don't understand how they've done it, but the escaping does work for the string, just not for NSLog.

So I guess you will have to come up with your own implementation of a log message if you really want backslashes.

Jorge Israel Peña
Is there any other way to be sure of this? Also, do you know any other way to represent a single literal backslash character and append it to a string?
Can you do something like `NSString *string = @"\\"; NSLog(@"%@", string);`
Tim
A: 

The strings and NSLog are working fine for me (iPhone SDK 3.1.2 and Xcode 3.2.1):

NSLog(@"\\"); // output is one backslash
NSLog(@"\\\\"); // output is two backslashes
NSLog(@"\\/Date(100034234)\\/"); // output is \/Date(100034234)\/

See this answer.

gerry3