You said you created your input line from an existing NSAttributedString as follows:
[NSString stringWithFormat:@"%@", nsattributedstring]
The %@ format NSAttributedString sends a description message to the NSAttributedString . The description method is not intended to create a string that can be easily converted back to an NSAttributedString object. It is designed to help programmers debug their code.
The process of converting an object to a string or an array of bytes in order to subsequently convert it back to an object is called serialization . Using the %@ or description method is usually not a good way to do serialization. If you really want to deserialize the string created by the description method, you will have to write your own parser. As far as I know, there is no API for this.
Instead, Cocoa provides a system designed to serialize and deserialize objects. Objects that can be serialized using this system comply with the NSCoding protocol. NSAttributedString objects correspond to NSCoding . Therefore, try serializing the original attribute string as follows:
NSMutableData *data = [NSKeyedArchiver archivedDataWithRootObject:nsattributedstring];
Save data (which is human readable binary, not UTF-8) where you need it. When you need to recreate the attributed string, do the following:
NSAttributedString *fancyText = [NSKeyedUnarchiver unarchiveObjectWithData:data];
If you are programming for OS X (not iOS), you have an alternative. You can turn the sent string into RTF (rich text format) that is human readable using the RTFFromRange:documentAttributes: method (which skips attachments) or RTFDFromRange:documentAttributes: (which includes attachments). You can then return the RTF data to the attribute string using initWithRTF:documentAttributes: or initWithRTFD:documentAttributes: These methods are not available on iOS.
If you are programming for iOS 7.0 or later , you can use -dataFromRange:documentAttributes:error: or fileWrapperFromRange:documentAttributes:error: to convert the assigned string to RTF / RTFD. You need to set NSDocumentTypeDocumentAttribute to NSRTFTextDocumentType or NSRTFDTextDocumentType in the attributes of the document. Use initWithData:options:documentAttributes:error: or initWithFileURL:options:documentAttributes:error: to convert back to NSAttributedString . These methods are part of the UIKit NSAttributedString add-ons .
source share