开发者

convert std::string to nsstring issue

Hi I use the following to convert std::string to NSString bu开发者_如何学JAVAt it return (null) while trying to display the value of the nsstring

I need it to return instead of (null) empty at conversion time any suggestion

StudyDate=[NSString stringWithCString:studyDate length:strlen(studyDate)]; 

any suggestion to avoid null values

best regards


Edit: The syntax @"string" is used only for constructing NSString. With std::string you should use the standard "string" syntax.

NSString* aConstantNSString = @"foo";
const char* aConstantCString = "foo";
std::string aConstantStdString = "foo";
CFStringRef aConstantCFString = CFSTR("foo");

  1. +stringWithCString:length: has been deprecated since the very early beginning of the iPhone SDK. If the string contains only ASCII characters, often you could use +stringWithUTF8String: instead.

  2. Your method works only when studyDate is a C string (i.e. const char*), but you said you have a std::string. There is no method to directly convert a std::string into an NSString. You must use .c_str() to create the C string first:

    StudyDate = [NSString stringWithUTF8String:studyDate.c_str()];
    

    (But the above shouldn't be the cause you're getting (null) because passing a std::string to +stringWithCString:length: or even strlen should give a compile-time error immediately.

    'error: cannot convert ‘std::string’ to ‘const char*’ in argument passing'
    

    So studyDate should already be a const char*. We need more context (code) to see what's going on.)


NSString objCString = @"this is my objective c string";
std::string cppString; // this is your c++ string or however you declared it blah blah blah

cppString = [objCString UTF8String];    
// this is the conversion of an NSString into a c++ string
// not sure if it will work for c strings but you can certainly try

thats all there is too it im afraid. all you need is just that one line of code. this was done in ios sdk 4.3 btw so im not sure if the coding will change if you appiled it elsewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜