Home > Software engineering >  Enforcing Line Breaks \n In Objective C
Enforcing Line Breaks \n In Objective C

Time:11-14

In Objective C I'm using the loadHTMLString to load a HTML string that has been inserted with a variable for JS. However, the string \n is not being included in the script.

For example, the code to be included:

'Product:A\nProduct:B\nProduct:C'

into java script as:

var source = 'Product:A\nProduct:B\nProduct:C'

However, in the completed HTML file the created script appears as:

var source = 'Product:A Product:B Product:C '

I need it to appear exactly as written for it to work. There are no substitutions:

var source ='Product:A\nProduct:B\nProduct:C'

Originally, I felt the problem was with formatting using: NSString stringWithFormat, but went with stringByAppendingString, but no luck - yet.

Thanks for your help

This is how the code appears when inserted by Obj C:

</head>
    <body>
        
        <h1>Absence Of Blood</h1>
        

        <canvas id="target-canvas"></canvas>
        <script>
            var canvas = document.getElementById('target-canvas')
            var source = 'Product:A 
Product:B 
Product:C 
'
            nomnoml.draw(canvas, source)
        </script>
        
    </body>

Obviously, it can only appear like this if code is entered in manually:

</head>
    <body>
        
        <h1>Absence Of Blood</h1>
        

        <canvas id="target-canvas"></canvas>
        <script>
            var canvas = document.getElementById('target-canvas')
            var source = 'Product:A\nProduct:B\nProduct:C'
            nomnoml.draw(canvas, source)
        </script>
        
    </body>

I think Objective C is formatting the \n into linefeed.

A simply fix could be replace \n with ^ in a var and use javascript function to read the code and replace the ^ with \n in var and feed it to: nomnoml.draw(canvas, modifiedSource)

Or find a way to STOP Obj-C from converting \n into linefeeds.

A list of NSString options are here:

NSStrings

but I didn't see anything that would make a difference.

CodePudding user response:

It seems like you want the literal text \ and n to appear in the output. To do this you need to escape the \n in your Objective-C strings.

So instead of something like this:

NSString *output = @"var source = 'Product:A\nProduct:B\nProduct:C'";

you need to escape the backslashes:

NSString *output = @"var source = 'Product:A\\nProduct:B\\nProduct:C'";

This will put a literal backslash followed by the letter "n" in the result instead of interpreting the \n special escape sequence as a newline character.

  • Related