Convert NSString to NSData

It’s a common question among iOS developers, how do I convert an NSString object to an NSData object?

The conversions is as simple as shown below:

NSString *str = @"";
NSData *nsdata = [str dataUsingEncoding:NSUTF8StringEncoding];

If for some reason you are dealing with content that has an unknown encoding, you may have better luck with something like this:

NSString *str2 = @"";
NSData *nsdata2 = [str2 dataUsingEncoding:[NSString defaultCStringEncoding]];

The defaultCStringEncoding returns a value that is based on the user’s default language among other factors.