4

I want to create an attributed string, then store it in NSUserDefaults, and then access it again and assign the attributed string to textView.attributedText. How do I go about this? Thanks in advance.

I don't know a lot of objective c, so I could not refer to this answer

Community
  • 1
  • 1
  • you would have to save just the string and re-add the effects, u can get the string from attString.string – Sean Lintern Apr 29 '16 at 13:57
  • I suppose you could use NSKeyedArchiver to store the attributed string. – Eric Aya Apr 29 '16 at 14:08
  • Possible duplicate of [Saving rich text in NSUserDefaults](http://stackoverflow.com/questions/18131373/saving-rich-text-in-nsuserdefaults) – fsb Apr 29 '16 at 14:17

1 Answers1

13

You have to convert your NSMutableAttributedString into NSData then you store it in NSUserDefaults.

    // Convert into NSData
    let data = NSKeyedArchiver.archivedDataWithRootObject(distanceMutableAttributedString)
    NSUserDefaults.standardUserDefaults().setObject(data, forKey: "yourStringIntoData")

    // Convert your NSData to NSMutableAttributedString
    let yourStringInData = NSUserDefaults.standardUserDefaults().objectForKey("yourStringIntoData") as? NSData
    let newStr = NSKeyedUnarchiver.unarchiveObjectWithData(yourStringInData!) as? NSMutableAttributedString

   // Assign it to your textView
    textView.attributedText = newStr
Chajmz
  • 729
  • 5
  • 11