[英]How can I save NSData to my database
I have a object of UILabel 我有一个UILabel对象
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
label1.text = @"LABEL AREA";
I want to save it in my databse(sqlite). 我想将其保存在我的databse(sqlite)中。
My idea is to convert this object to a NSData using 我的想法是使用以下方法将该对象转换为NSData
[NSKeyedArchiver archivedDataWithRootObject:label1]; //step1
and convert this NSData to a NSString(step2), then save that NSString to the database(step3). 并将此NSData转换为NSString(步骤2),然后将该NSString保存到数据库(步骤3)。
When I need my UILabel. 当我需要UILabel时。 I can get the NSString from database, convert it to NSData, and use
我可以从数据库中获取NSString,将其转换为NSData,然后使用
[NSKeyedUnarchiver unarchiveObjectWithData:];
to get my UILabel. 得到我的UILabel。
But I have a problem in "step 2". 但是我在“第2步”中遇到了问题。 When I use
当我使用
NSString *strWithEncode = [[NSString alloc] initWithData:dataRaw encoding:NSUTF8StringEncoding];
I get a null object. 我得到一个空对象。 I don't know the reason.
我不知道原因 Why?
为什么?
Thanks a lot! 非常感谢!
You could either a) Store the data as a BLOB
or b) Store the text of the string instead of the actual string. 您可以a)将数据存储为
BLOB
或b)存储字符串的文本而不是实际的字符串。 B
seems like a better choice because you will be storing less data, and the contents of the DB will be human readable, should you need that information for debugging later on. B
似乎是一个更好的选择,因为您将存储较少的数据,并且如果以后需要该信息以进行调试,则DB的内容将易于阅读。
Because the NSData represents an encoded UILabel and not a UTF-8 encoded NSString, trying to initialize a UTF-8 string from the data will almost certainly not work. 因为NSData代表一个编码的UILabel而不是一个UTF-8编码的NSString,所以几乎肯定不能从数据中初始化一个UTF-8字符串。 If you absolutely have to store the data as a string, try using some form of data-to-string encoding.
如果绝对必须将数据存储为字符串,请尝试使用某种形式的数据到字符串编码。 Try using base32 or base64.
尝试使用base32或base64。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.