4

I can convert from rtf string to attributed string using following:

 NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];

Now how can i convert back from attributedString to rtf string?

1
  • If there is no method to do so, then I doubt you can.
    – trojanfoe
    Jun 10, 2014 at 6:27

1 Answer 1

15

You want to use -dataFromRange:documentAttributes:error:

NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"YOLO" attributes:nil];
NSData *data = [str dataFromRange:(NSRange){0, [str length]} documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType} error:NULL];
[data writeToFile:@"/me.rtf" atomically:YES];

Of course you'd want to have some attributes instead of "YOLO", but you get the idea.

Also, if you're looking to simply write this to disk, then fileWrapperFromRange:documentAttributes:error: might even be a better option. You can find more about reading and writing from the Attributed String Programming Guide

2
  • I Used NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSRTFTextDocumentType ,NSDocumentTypeDocumentAttribute, nil]; NSData *rtfData = [txtView.attributedText dataFromRange:NSMakeRange(0, txtView.attributedText.length) documentAttributes:documentAttributes error:NULL]; NSString *rtfString = [[NSString alloc] initWithData:rtfData encoding:NSUTF8StringEncoding];
    – Hassy
    Jun 10, 2014 at 6:43
  • 1
    @ghazi_jaffary That's what I'm here for Jun 10, 2014 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.