Here is a code sample that does what you want. My case was this: I wanted to add log-messages into a log-file, where each log line is terminated by \n
(that's how my logger works). However - I sometimes need to have multi-line messages in the log, so they cannot contain \n - or they'll break the log file format. So... Here I replace all the "newlines" with "NSLineSeparatorCharacter":
NSString *logMessage // multi-paragraph string message containing all kinds of line and paragraph breaks.
NSString *singleParagraphMultiLineMessage =
[[logMessage componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]
componentsJoinedByString:@"\u2028"];
Attention: If you try to display this string via its description
, it will change the NSLineSeparator back to \n
For example: if you'll try to use:
NSString *test = [NSString stringWithFormat:"%@", singleParagraphMultiLineMessage];
NSLog(@"%@", singleParagraphMultiLineMessage);
or even po singleParagraphMultiLineMessage
in the debugger -
the result will no longer include NSLineSeparatorCharacter. Only if you export it to NSData and save to file - or else extract its contents in UTF8 - you'll see that it works fine. It took me a while to understand why this was happening.
Just to make the answer complete, the NSLineSeparatorCharacter is defined, part of the following enumerator, in Appkit/NSText.h, like thus:
/* Various important Unicode code points */
enum {
NSEnterCharacter = 0x0003,
NSBackspaceCharacter = 0x0008,
NSTabCharacter = 0x0009,
NSNewlineCharacter = 0x000a,
NSFormFeedCharacter = 0x000c,
NSCarriageReturnCharacter = 0x000d,
NSBackTabCharacter = 0x0019,
NSDeleteCharacter = 0x007f,
NSLineSeparatorCharacter = 0x2028, // <-- here it is.
NSParagraphSeparatorCharacter = 0x2029
};
But NOT in UIKit/NSText.h which is miserably empty in comparison with its MacOS counterpart. I wonder why apple neglected iOS developers so badly with this one. Maybe they don't favor NSText, and want developers to move away from using it?. Still - you're welcome to copy that enum, and paste it into your code, thus to achieve MacOS/iOS code-compatibility.