Picture of Brian Love wearing black against a dark wall in Portland, OR.

Brian Love

Newlines stored in NSString attributes in Core Data

I recently ran into an interesting issue that I thought I would write about. I have an entity in Core Data that stores an explanation. The explanation attribute is a string type, and I am using this value to display the text within a UITextView. I have newline characters (n) in my data.

I was expecting the newlines to then be shown in the resulting UITextView when I set the text property to the value stored in my database. The problem is that the newlines were being displayed in the UITextView:

Newlines in UITextView

The simple solution is to replace instances of “n” with an actual newline character. It’s a one-liner:

[explanation stringByReplacingOccurrencesOfString:@"\n" withString:@"n"];

Here we simply call the stringByReplacingOccurrencesOfString:withString: method on the string that we retrieved from core data.