简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM