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

时间:2016-04-29 13:56:50

标签: ios string swift nsuserdefaults nsattributedstring

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

我不太了解很多目标c,所以我不能参考this answer

1 个答案:

答案 0 :(得分:12)

您必须将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