-1

I have this code who get a file inside my iOS, convert it to an NSData and converts it into a NSString:

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

NSData *files = [filemgr contentsAtPath:databasePath];

NSData *databuffer = [filemgr contentsAtPath:databasePath];

NSString *string = [NSString stringWithFormat:@"%@",databuffer];

All I wanna know is if there is the possibility to convert this NSString to NSData and back through the NSData using NSFileManager and resave the file in its original format?

user3781174
  • 245
  • 5
  • 16

2 Answers2

1

The stringWithFormat is an expensive way to call NSData's description method. This simply produces a hex dump. And, we are advised, Apple makes no guarantees that description methods produce a format that will not be changed in the future, so it should only be used for diagnostic purposes.

If you want to convert an NSData to string format so it can be transmitted as a string you should use Base64 encoding. If the NSData is actually character info it should be converted to NSString using the appropriate string encoding.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
0

To convert an NSData to an NSString use:

NSString *string = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];`

Assuming the data was encoded with NSUTF8StringEncoding (a good bet).

To convert an NSString to an NSData:

NSData *data = [string dataUsingEncoding: NSUTF8StringEncoding];`

Assuming the data encoding should be NSUTF8StringEncoding (a good bet).

You need to do some research/studying the difference between NSData and NSString.

zaph
  • 111,848
  • 21
  • 189
  • 228