NSString to ByteArray and back
I am implementing an interface, which specifies writeBytes()
and readBytes()
on a file.
The data has to be transported as JSON.
For readBytes
I do the following:
NSFileHandle readDataOfLength
- to read from a fileNSString initWithData: encoding:
- to specify a given encodingNSString getBytes:buffer
- put each
buffer[i]
into a JSON array for transport :[116,101,115,116]
for example"test"
as UTF-8
On the other hand writeBytes
should be doing about the same:
- Parse the JSON array to a
NSArray开发者_JS百科
NSArray getObjects:buffer
- the conversion up to this point is successfulNSString initWithBytes:buffer length: encoding:
- is not working, the return value is nullNSData dataUsingEncoding:
NSFileHandle writeData
Apparently NSString initWithBytes
cannot handle buffers with content such as [116,101,115,116]
. Is there any other way to convert a NSString
into a byte array and back ?
Thanks
Have you verified that the bytes within the array are a valid UTF-8 representation of a string? (http://en.wikipedia.org/wiki/UTF-8)
If not, you'll get back nil:
#import <Foundation/Foundation.h>
int
main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
char ary[] = { 116, 101, 115, 116, 255 };
NSString *s = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSASCIIStringEncoding];
NSString *s2 = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSUTF8StringEncoding];
NSLog(@"s: %@, s2: %@", s, s2);
[pool release];
}
When run, this prints:
2010-01-13 14:08:23.315 a.out[50653:903] s: testÿ, s2: (null)
Are you using the NSUnicodeStringEncoding encoding ? If so, then you may have to prefix your bytes with a valid B.O.M (See NSString reference, section "Interpreting UTF-16-encoded data").
Have you made a test with the NSASCIIStringEncoding to check that your code works for simple case ?
精彩评论