Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString with \0

What is the best way to initiate NSString that contains @"\0"?

NSString* foo = @"bar\0";

causes 'CFString literal contains NUL character' warning.

like image 913
fish potato Avatar asked Dec 10 '25 09:12

fish potato


2 Answers

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).

like image 86
dreamlax Avatar answered Dec 12 '25 22:12

dreamlax


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!