How to save (and retrieve) NSAttributedString in a NSDictionary

岁酱吖の 提交于 2019-12-08 02:52:13

问题


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.



来源:https://stackoverflow.com/questions/22312708/how-to-save-and-retrieve-nsattributedstring-in-a-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!