How do I convert a NSString into a std::string?

后端 未结 3 890
别跟我提以往
别跟我提以往 2020-12-07 20:03

I have an NSString object and want to convert it into a std::string.

How do I do this in Objective-C++?

3条回答
  •  孤城傲影
    2020-12-07 20:20

    As noted on philjordan.eu it could also be that the NSString is nil. In such a case the cast should be done like this:

    // NOTE: if foo is nil this will produce an empty C++ string

    // instead of dereferencing the NULL pointer from UTF8String.

    This would lead you to such a conversion:

    NSString *foo = @"Foo";
    std::string bar = std::string([foo UTF8String], [foo lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
    

提交回复
热议问题