Your syntax is correct. NSString just doesn't handle NULL
bytes well. I can't find any documentation about it, but NSString will silently ignore %c
format specifiers with an argument of 0
(and on that note, the character constant '\0'
expands to the integer 0
; that is correct). It can, however, handle \0
directly embedded into an NSString literal.
See this code:
#import <Cocoa/Cocoa.h>
int main (int argc, char const *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *stringByChars = [NSString stringWithFormat:@"-%c%c%c%c-",0,0,0,0];
NSString *stringByEscapes = [NSString stringWithFormat:@"-\0\0\0\0-"];
NSLog(@" stringByChars: \"%@\"", stringByChars);
NSLog(@" len: %d", [stringByChars length]);
NSLog(@" data: %@", [stringByChars dataUsingEncoding:NSUTF8StringEncoding]);
NSLog(@"stringByEscapes: \"%@\"", stringByEscapes);
NSLog(@" len: %d", [stringByEscapes length]);
NSLog(@" data: %@", [stringByEscapes dataUsingEncoding:NSUTF8StringEncoding]);
[pool drain];
return 0;
}
returns:
stringByChars: "--"
len: 2
data: <2d2d>
stringByEscapes: "-
len: 6
data: <2d000000 002d>
(Note that since the stringByEscapes
actually contains the NULL
bytes, it terminates the NSLog string early).