Phil0
Phil0

Reputation: 13

Realm: How to use line breaks in database String entry?

I am using a Realm DB in my iOS app and wanted to have a long entry broken up by specifically placed line breaks. I inserted \n into the text but when displayed, these are treated as text rather than newlines.

Is there a way to insert new lines into the String stored in the database that will be recognised when the String is displayed?

Upvotes: 1

Views: 419

Answers (1)

jpsim
jpsim

Reputation: 14409

Realm stores whatever you put in there, so if you're storing Swift.Strings, it'll store them exactly byte-for-byte using UTF8 encoding. So really this is a question of how to properly escape newlines in a Swift String.

print("a\nb")
// Prints:
// a
// b

Same thing goes for Realm:

import RealmSwift

class MyModel: Object {
    dynamic var stringProperty = ""
}
let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "TemporaryRealm"))
try! realm.write {
    let object = MyModel()
    object.stringProperty = "a\nb"
    realm.add(object)
}
print(realm.objects(MyModel).first!.stringProperty)
// Prints:
// a
// b

Upvotes: 1

Related Questions