Cocoa: How to save NSAttributedString to JSON

前端 未结 3 981
梦毁少年i
梦毁少年i 2021-02-10 06:44

I have a NSAttributedString object as a property of a custom object. I need to save this custom object to the disk in JSON format. Later I need to

3条回答
  •  一个人的身影
    2021-02-10 07:25

    You could use this simple code snippet to convert NSAttributedString to XML without actually parsing NSAttributedString. This can be a human-readable alternative to JSON if you can afford verbose text output.

    It can be also used for decoding back to NSAttributedString.

        let data = NSMutableData()
    
        let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.outputFormat = .XMLFormat_v1_0
        textView.attributedText.encodeWithCoder(archiver)
        archiver.finishEncoding()
    
        let textAsString = NSString(data: data, encoding: NSUTF8StringEncoding)'
    

提交回复
热议问题