在 NSUserDefaults 中保存富文本 [英] Saving rich text in NSUserDefaults

查看:55
本文介绍了在 NSUserDefaults 中保存富文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Objective-C 的新手,我找不到问题的答案.我编写了一个使用文本字段输入一些文本的简单程序,然后使用:

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?

推荐答案

SaveFBCover1 正在从 Cover1.stringValue 获取 NSString,而不是 NSAttributedString>,因为 .看起来您的代码正确保存了该字符串,并且您再次加载时可能会取回该字符串,但是您不会获得属性,因为您没有以属性字符串开头,也没有获得属性文本视图中的文本并单独保存.

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.

您可以使用

SaveFBCover1 = Cover1.attributedStringValue;

但是,您将不得不做更多的工作来保存和加载字符串(不过不多).NSAttributedString 不是您可以直接保存在 NSUserDefaults 中的类型之一,因此您需要将其序列化为 NSData 的实例第一的.您可以使用带键的归档程序轻松地做到这一点.阅读 档案和序列化编程指南中的键控档案.

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.

这篇关于在 NSUserDefaults 中保存富文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆