2

I would like to save objects that have a NSAttributedString property to Realm. What is the best way to do this?

Melodius
  • 2,505
  • 3
  • 22
  • 37
  • 1
    Realm is for storing data models. NSAttributedString is for display. Why do you feel the need to do this? You should be storing your data in Realm (ie. the raw string) and ought to be able to generate the attributed string from your data. – Connor Neville Dec 20 '16 at 18:11
  • If there is an easy way to convert the NSAttributedString to a string that preserves all attributes in both conversions, then that would be fine. My app has notes that can contain formatted text which I want to store. – Melodius Dec 20 '16 at 19:08
  • 1
    Create an Realm Object to save attributes , basically attributes are key value pair. Save both of them and establish a relationship to the original string. Retrieve the string and retrieve the attributes. Then you can form the NSAttributedString and show it – jatin kumar malana Dec 20 '16 at 19:27
  • You should be able to do what you want by following this idea: http://stackoverflow.com/a/37456993/2227743 – Eric Aya Dec 21 '16 at 14:33
  • 1
    I found NSKeyedArchiver to be much easier to work with than the HTML option. This answer has a good example: https://stackoverflow.com/a/36940864/4139760. – blwinters Jun 06 '17 at 20:35

1 Answers1

0

While Realm can store NSString values, it doesn't support NSAttributedString. As such, it will be necessary for you to convert your NSAttributedString to a version that can be represented as an NSString when saving it to Realm, and then convert it back when required.

From doing a quick search on SO, converting an NSAttributedString to HTML might be the easiest to preserve the formatting of the attributed string.

You could also add convenience methods to your Realm object model that will internally perform the conversion.

Community
  • 1
  • 1
TiM
  • 15,812
  • 4
  • 51
  • 79
  • This is a fine thought; however, in practice, NSAttributedString's built-in conversion from HTML is slow, on the order of 100ms for a one-paragraph blurb. It may not be performed on a background thread, either. You can use the same code but ask for RTF format. This causes a ~100ms hiccup on the first encoding, but after that both encoding and decoding are typically < 1ms. The disadvantage is that the RTF is quite bulky. – GSnyder May 23 '18 at 00:50
  • 1
    Fair enough! That was one example. It doesn't have to be the built-in converter, and it doesn't even have to be HTML. `NSAttributedString` also conforms to `NSSecureCoding` so you could also just serialize it to `NSData` and store it that way. :) – TiM May 23 '18 at 09:12