How to save (and retrieve) NSAttributedString in a NSDictionary

感情迁移 提交于 2019-12-06 11:30:42

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

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.

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