Flaviu Simihaian's Blog - Entrepreneur and Developer

How to Write a Multi-line NSString in Objective-C

Say you have some HTML you need to cram into a WebView in iOS. You can create a .html file but then you can’t pass variables from your code.

So, you try inlining it. Except you find out that Objective-C does not have like a triple quote or some other multi-line escaping.

You need to end every line with a backslash. So, this code:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <title>U.S. Population</title>
    <script type="text/javascript" src="../../d3.v2.js"></script>
    <link type="text/css" rel="stylesheet" href="population.css"/>
  </head>
  <body>
    <div id="chart"></div>
    <script type="text/javascript" src="population.js"></script>
  </body>
</html>

needs to become this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@" \
<!DOCTYPE html> \
<html> \
<head> \
<title>U.S. Population</title> \
<script type=\"text/javascript\" src=\"d3.v2.min.js\"></script> \
<link type=\"text/css\" rel=\"stylesheet\" href=\"population.css\"/> \
</head> \
<body> \
<div id=\"chart\"></div> \
<script type=\"text/javascript\" src=\"population.js\"></script> \
</body> \
</html> \
"

You don’t want to do that manually. So I made a little tool that converts one to the other. Check it out at MultiLineObjC.herokuapp.com.

Hope this saves you some time.

Comments

Fork Flaviu on GitHub