0

Is there a way to have double-quotation marks in strings in Objective C without escaping them?

In PHP you can wrap a string in single quotation marks, in which case you do not have to escape anything in the string.

CommaToast
  • 11,370
  • 7
  • 54
  • 69

3 Answers3

1

The only chance is to compile your source as Objective-C++ file (file suffix ".mm"). Then the C++ raw string literals are also accepted when defining an NSString, for example

NSString *str = @R"(Hello"World\n)";

has the 13 characters

H e l l o " W o r l d \ n

But that feature is only available in (Objective-)C++ source files, not in (Objective-)C.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

Unfortunately, there is no way (that I know of) to have an unescaped quotation mark inside a string in Objective-C. You can get a quotation mark using unicode or some other trick, but I believe that you want a less ugly way to write a quotation inside a string, not an even uglier one :)

P.S. Just for fun I've just tried to use a unicode escape sequence (@"\u0022"), and it turned out it is forbidden.

Community
  • 1
  • 1
FreeNickname
  • 7,398
  • 2
  • 30
  • 60
  • 1
    The preprocessor converts `\uxxxx` escapes to their actual characters before the compiler does its job. So `@"\u0022"` ends up being the same as `@"""`. So you need the backslash in both cases. – rmaddy Dec 30 '15 at 21:05
  • @rmaddy, thank you for the explanation) I didn't know it is done at the preprocessor level before. It explains why it is forbidden. There is a catch however. Xcode just refuses to compile "incorrect" escape sequences, without trying to replace them. Otherwise `@"\u005c\u0022"` would work. And if we just add a backslash (`@"\\u0022"`), the string will be treated as a plaintext: `"\u0022"`. "How hard can it be to use unicode for quotes inside a string?" :) – FreeNickname Dec 30 '15 at 21:26
  • 2
    @rmaddy, that's not true. You can ask for the preprocessor output (e.g. using `cc -E`) and `\uxxxx` escape sequences in string literals remain. It's the compiler which handles those. – Ken Thomases Dec 30 '15 at 22:09
-1

Curly quotes don't require escaping, and generally look better for messages presented to the end user:

    NSString *str = @"Hello, “World”!";
Dave Batton
  • 8,795
  • 1
  • 46
  • 50