15

Is there any way to declare a NSString in multiple lines? I want to write HTML code and store it into a NSString, and in multiple lines de code will be more readable. I want to do something like this:

NSString *html = @"\<html\>"
 + @"\<head\>"
 + @"\<title\>The Title of the web\</title\>"
 + @"\</head\>"
 + @"\<body\>"
[...]
pasawaya
  • 11,515
  • 7
  • 53
  • 92
Jimmy
  • 873
  • 3
  • 12
  • 29
  • 2
    Duplicate of http://stackoverflow.com/questions/797318/how-to-split-a-string-literal-across-multiple-lines-in-c-objective-c – rid Oct 03 '11 at 10:20
  • Does this answer your question? [How to split a string literal across multiple lines in C / Objective-C?](https://stackoverflow.com/questions/797318/how-to-split-a-string-literal-across-multiple-lines-in-c-objective-c) – Alex Cohn Dec 15 '21 at 17:38

4 Answers4

42

This is an example:

NSString *html = [NSString stringWithFormat:@"<html> \n"
                          "<head> \n"
                          "<style type=\"text/css\"> \n"
                          "body {font-family: \"%@\"; font-size: %dpx;}\n"
                          "img {max-width: 300px; width: auto; height: auto;}\n"
                          "</style> \n"
                          "</head> \n"
                          "<body><h1>%@</h1>%@</body> \n"
                          "</html>", @"helvetica", 16, [item objectForKey:@"title"], [item objectForKey:@"content:encoded"]];
Raptor
  • 53,206
  • 45
  • 230
  • 366
0

I know it's Objective-C question but it's pretty easy with Swift:

let multiline = """
first line
second line
without escaping characters
""";
0
NSString * html = @"line1\
line2\
line3\
line4";

And beware of tabs/spaces in the beginning of each line - they do count in this case.

Kibernetik
  • 2,947
  • 28
  • 35
0

Create an NSString with multiple lines to mimic a NSString read from a multi-line text file.

NSString * html = @"line1\n\
line2\n\
line3\n\
line4\n";

A \n on the last line is up to you.

Alex Popadich
  • 141
  • 2
  • 4