How to save (and retrieve) NSAttributedString in a

2019-05-23 05:12发布

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:?

2条回答
Melony?
2楼-- · 2019-05-23 05:50

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).

查看更多
成全新的幸福
3楼-- · 2019-05-23 06:10

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.

查看更多
登录 后发表回答