The normal way of saving an NSAttributedString
is to use RTF, and RTF data is what the -dataFromRange:documentAttributes:error:
method of NSAttributedString
generates.
However, the RTF format has no support for custom attributes. Instead, you should use the NSCoding
protocol to archive your attributed string, which will preserve the custom attributes:
//asssume attributedString is your NSAttributedString
//encode the string as NSData
NSData* stringData = [NSKeyedArchiver archivedDataWithRootObject:attributedString];
[stringData writeToFile:pathToFile atomically:YES];
//read the data back in and decode the string
NSData* newStringData = [NSData dataWithContentsOfFile:pathToFile];
NSAttributedString* newString = [NSKeyedUnarchiver unarchiveObjectWithData:newStringData];
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…