Rameez Hussain
Rameez Hussain

Reputation: 6754

Converting NSData to NSAttributedString on iOS

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.

Upvotes: 1

Views: 2382

Answers (2)

Duncan C
Duncan C

Reputation: 131418

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.

Upvotes: 7

Nate Lee
Nate Lee

Reputation: 2842

Try this

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

Class reference here

Upvotes: 1

Related Questions