How can I save NSData to my database
I have a object of UILabel
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
label1.text = @"LABEL AREA";
I want to save it in my databse(sqlite).
My idea is to convert this object to a NSData using
[NSKeyedArchiver archivedDataWithRootObject:label1]; //step1
开发者_如何学运维
and convert this NSData to a NSString(step2), then save that NSString to the database(step3).
When I need my UILabel. I can get the NSString from database, convert it to NSData, and use
[NSKeyedUnarchiver unarchiveObjectWithData:];
to get my UILabel.
But I have a problem in "step 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. 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.
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. 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.
精彩评论