NSString with \0
What is the best way to initiate NSString that contains @"\0"?
NSString* foo = @"bar\0开发者_如何学C";
causes 'CFString literal contains NUL character' warning.
NSString
objects are for text. Consider using an NSData
or NSMutableData
object if you wish to have non-text data in amongst textual data (for example, when it is to be written to a socket or saved to a file).
You can put a NUL character into an NSString
instance, here's one example:
int main() {
NSString *string = [NSString stringWithFormat: @"Hello%CWorld!", 0];
NSData *bytes = [string dataUsingEncoding: NSUTF8StringEncoding];
NSLog(@"string: %@", string);
NSLog(@"bytes: %@", bytes);
return 0;
}
Be aware that at surprising points in your app's execution, the string will be converted into a C string (or something similar) for interacting with lower-level API, and that this will cause the string to be truncated. As an example, the output of the above program is this:
2011-06-02 09:18:30.307 Untitled[294:707] string: Hello
2011-06-02 09:18:30.309 Untitled[294:707] bytes: <48656c6c 6f00576f 726c6421>
Showing that the NSString
itself is completely intact but that NSLog()
won't display it correctly.
精彩评论