How to use store and use an NSMutableAttributedString in NSUserDefaults

こ雲淡風輕ζ 提交于 2019-11-27 03:42:33

问题


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


来源:https://stackoverflow.com/questions/36940275/how-to-use-store-and-use-an-nsmutableattributedstring-in-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!