问题
I'm a new to Objective-C and I can't find an answer to my problem. I've written a simple program using a text field to enter some text, then use:
SaveFBCover1 = Cover1.stringValue;
DefaultCover1 = [NSUserDefaults standardUserDefaults];
[DefaultCover1 setObject:SaveFBCover1 forKey:@"SaveCover1"];
[DefaultCover1 synchronize];
to save it. After that, it does this
DefaultCover1 = [NSUserDefaults standardUserDefaults];
loadFBCover1 = [DefaultCover1 objectForKey:@"SaveCover1"];
FBCoverImageText = [NSString stringWithFormat:@"%@", loadFBCover1];
to load it. But what I want is to save and load rich text with colors, fonts and so on.
For some reason, it fails to save or load properly. Can someone point out my mistake?
回答1:
SaveFBCover1
is getting an NSString from Cover1.stringValue
, not an NSAttributedString
, because the . It looks like your code saves that string properly, and you're probably getting the string back when you load it again, but you won't get attributes because you didn't start with an attributed string, nor did you get the attributes of the text in the text view and save them separately.
You can get an attributed string by using
SaveFBCover1 = Cover1.attributedStringValue;
However, you're going to have to do a little more work to save and load the string (not much, though). NSAttributedString
isn't one of the types that you can save directly in NSUserDefaults
, so you'll need to serialize it into an instance of NSData
first. You can do that quite easily using an keyed archiver. Read about Keyed Archives in the Archives and Serializations Programming Guide.
来源:https://stackoverflow.com/questions/18131373/saving-rich-text-in-nsuserdefaults