如何在 NSUserDefaults 中使用存储和使用 NSMutableAttributedString

How to use store and use an NSMutableAttributedString in NSUserDefaults

我想创建一个属性字符串,然后将其存储在 NSUserDefaults 中,然后再次访问它并将属性字符串分配给 textView.attributedText。我该怎么做?提前致谢。

我不太了解objective c,所以无法参考this answer

您必须将 NSMutableAttributedString 转换为 NSData,然后将其存储在 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