1

In my app, I am trying to archive an NSAttributedString object so I have successfully converted it to an NSData object using the following code:

NSData *attrStrData = [attrStr dataFromRange:NSMakeRange(0, attrStr.length) documentAttributes:NULL error:nil];

Now I want to convert this NSData object back to NSAttributedString. I believe on OSX you have some methods for this, but are there any on iOS? I found NSAttributedString+Encoding, but there seems to be less support for it and it is not available on CocoaPods. Any suggestions are welcome.

Neeku
  • 3,646
  • 8
  • 33
  • 43
Rameez Hussain
  • 6,414
  • 10
  • 56
  • 85
  • http://stackoverflow.com/questions/2626667/saving-custom-attributes-in-nsattributedstring ? – Larme May 23 '14 at 13:24
  • How about looking into [Text Storage class](https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSTextStorage_Class/Reference/Reference.html) - ```NSTextStorage```? – raurora May 23 '14 at 13:32

2 Answers2

7

NSAttributedString conforms to NSCoding. Just use code like this:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject: myAttrString];

Then when you want to convert the NSData back to a string:

NSAttributedString *myAttrString = 
  [NSKeyedUnarchiver unarchiveObjectWithData: data];

Easy, and the same code works on both Mac and iOS.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Hmm. I tried this, but I get the following error - -[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x17d68fd0 – Rameez Hussain May 23 '14 at 14:06
  • @RameezHussain, you must be doing something wrong then. I've used this technique multiple times. Edit your original question with an update showing your new code and the line that's throwing the error. – Duncan C Apr 07 '16 at 10:51
1

Try this

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithData:attrStrData options:nil documentAttributes:nil error:nil];

Class reference here

Nate Lee
  • 2,842
  • 1
  • 24
  • 30