How to save (and retrieve) NSAttributedString in a

2019-05-23 05:27发布

问题:

I am trying to save and retrieve XML data to a file.

For this purpose I am using NSDictionary's writeToFile:
The question is, how to write and retrieve an attributed string to and from a file on disk using NSDictionary's writeToFile:?

回答1:

NSAttributedString is not a property list object, so writeToFile: won't work.

It does, however, conform to NSCoding, so you can write it to an archive with your dictionary as the root object (assuming that all the other objects in the dictionary also conform).



回答2:

If you need something more portable than archived object consider using RTF representation of NSAttributedString:

    NSAttributedString* attrString = [[NSAttributedString alloc] initWithString:@"Attributed String" 
        attributes:@{ NSForegroundColorAttributeName: [NSColor redColor]}];
    NSData* rtfData = [attrString RTFFromRange:NSMakeRange(0, attrString.length) documentAttributes:nil];
    [rtfData writeToFile:@"string.rtf" atomically:YES];

You can read it back:

    NSData* rtfData = [NSData dataWithContentsOfFile:@"string.rtf"];
    NSAttributedString* attrString = [[NSAttributedString alloc] initWithRTF:rtfData documentAttributes:nil];

Also since RTF is a simple text format you can convert RTF data to NSString and store it as plain text in a dictionary.