Reputation: 153
Is there any way to store a NSString in a NSData maintaining the SAME data?
Example (this is fine, but it's not what I need):
NSString *tmpString = @"Hello World!";
NSData *nsdataString = [tmpString dataUsingEncoding:NSUTF8StringEncoding];
I need something like this (that obviously fail):
NSData nsdataString = @"Hello World!";
In few words: I need to use NSData like if it was the SAME of a NSString (like using a cast operator). This approach is very useful to preload an encrypted core data sqlite database (in a NSString) and decrypt only when the user access to the fields of persistent store.
To decrypt I use:
NSData *decryptedData = [encryptedData AES256DecryptWithKey:keyString];
Where encryptedData is a NSData and keyString is a NSString.
Thanks a lot to everybody!
Upvotes: 0
Views: 264
Reputation: 490
Short answer: no.
An NSData object is a wrapper for a raw sequence of ones and zeroes. An NSString object is a wrapper for an array of Unicode characters in an encoding that is not exposed.
Depending on the string encoding used to write the NSData, it could represent a number of different strings. For example: little-endian UTF16 and big-endian UTF16 strings representing the same characters will look different, and trying to parse a UTF-8 string as UTF-16 will give you gibberish.
This is why you always have to convert an NSData to an NSString before treating it as a string: because until you specify the encoding, it isn't a string; it's just raw ones and zeros.
I'm not sure from your question exactly why you want to do this, but it's possible you can accomplish what you need to with a C string (instead of an NSString), which you can get with NSData's -bytes method. However, you still need to bear the encoding in mind if you want to end up with a useful string at any point.
Upvotes: 0