views:

163

answers:

1

I am pulling data into my iphone application using xml. The xml value is then placed in a variable.

example variable:

123 London road \n London \n England

The variable is then set as a label.

I want the line breaks to appear in the label, instead it is printing \n.

If i manually set the label value

locationLabel.text = @"123 London road \n London \n England"

It works as i want it to.

Can anyone explain this?

+5  A: 

You have to replace the substrings \n (consisting of the characters \ and n) with the actual linebreak character (in C-sources expressed by \n), e.g. by using NSStrings replace methods:

NSString *res = [myStr stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
Georg Fritzsche
+1 Ha ha, thanks for that. I have exactly the same issue of replacing escape sequences in a completely different context and I was pondering how I was going to do that. That's a nice clean solution
JeremyP
Alas, it doesn't work. Consider the string "\\n". In that situation, it is the second backslash that should be escaped, not the n.
JeremyP
I don't understand your problem, the above works fine for this situation - e.g. for `myStr = @"a \\n b";`. @jer
Georg Fritzsche
Because you don't want to end up with a new line in the sequence \\n, you want to end up with a backslash followed by n.
JeremyP
It's slightly confusing because the compiler converts `@"\\n"` to the two literal characters \ and n. However, I was talking about the sequence of three literal characters (after the compiler has done its stuff) \ \ and n. `Try [@"\\\\n" stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];`
JeremyP
If this is how your context looks, then the above is not the solution for you. From the OP i just know there is an escape code for line-breaks, there is no mention of any other. @jer
Georg Fritzsche