user6209153
user6209153

Reputation:

How to use store and use an NSMutableAttributedString in NSUserDefaults

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

Upvotes: 4

Views: 2212

Answers (1)

Chajmz
Chajmz

Reputation: 749

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

Upvotes: 13

Related Questions