Jimmy
Jimmy

Reputation: 893

Declare a NSString in multiple lines

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\>"
[...]

Upvotes: 15

Views: 11964

Answers (4)

Alex Popadich
Alex Popadich

Reputation: 141

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.

Upvotes: 0

Kibernetik
Kibernetik

Reputation: 3028

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

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

Upvotes: 0

Marcin Mierzejewski
Marcin Mierzejewski

Reputation: 726

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

let multiline = """
first line
second line
without escaping characters
""";

Upvotes: 0

Raptor
Raptor

Reputation: 54212

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"]];

Upvotes: 42

Related Questions