How to use store and use an NSMutableAttributedStr

2019-01-18 16:22发布

问题:

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

回答1:

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