Question

I have an object that contains a large amount of variables that needs to be saved locally as well as onto a database. This object would be serialized and stored locally using NSKeyedArchiver (in conjunction with CryptoCoder from https://github.com/nicklockwood/CryptoCoding).

Now I'm trying to store the data in the db (cloudant.com). I can send the data up using NSData directly, storing (eg, < F60323 04A525 ... ... 6D3301>) in the database, but reading that back I have no idea how to convert it back into NSData. Using NSString with encoding produces a null result.

Because the serialized data is written in a file that follows the plist format, I tried converting it into a NSDictionary using NSPropertyListSerialization and sending that up instead, but the conversion was not accurate.

Advice needed.

Était-ce utile?

La solution

The NSData (eg, < F60323 04A525 ... ... 6D3301 >) is in hex format. I believe you are calling the [NSData description] method to get that result. It is not suppose to be use for serialization, although serializing isn't impossible. (Just need to write a custom hex to data converter)

There's many way to transfer data over the net. I am assuming you are using HTTP for your transport layer. I list 2 ways this can be done

JSON way (also work for plist, although it support more data type)

Write custom serializer and deserializer that convert the object to be serialise into an object that NSJSONSerializer can serialize into JSON successfully.

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

Reference:

Raw NSData through HTTP

Uploading raw NSData (from NSCoding) through HTTP is usually done with either HTTP POST of application/octet-stream or multipart/form-data.

If you want to POST with other method like application/x-www-form-urlencoded, you need serialize it to web friendly encoding like base64 or hexadecimal. I recommend using Base64. iOS doesn't comes with Base64 encoder and decoder but I had written one (Based on Mattt Thompson's AFNetworking implementation). I know other people had written similar methods which I have review and find out that Mattt Thompson (and subsequently my derived base64 decoder code) are clean, readable and as few logic as possible.

Base64 Encoding and Decoding implementation in Objective-C

Make sure you when you retrieve back the data from your server, if it is (base64 or hex) encoded, decode first. Serialize the decoded data to JSON, Property List or NSCoding, dependent on your implementation.

Basically, reverse your serialization steps.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top