When working with Objective-C++, I often find myself using initWithCString to convert from std::string to NSString. To simplify the process, I created a category on NSString as follows:
@implementation NSString (NSStringFromCPP)
+(NSString*)stringFromCppString:(std::string)cppString
{
return [[NSString alloc] initWithCString:cppString.c_str() encoding:NSStringEncodingConversionAllowLossy];
}
-(std::string)cppString
{
return std::string([self cStringUsingEncoding:NSStringEncodingConversionAllowLossy]);
}
@end
This allows for a fairly easy conversion between NSString and std::string in both directions. It seems there has to be a way to implicitly convert from std::string to NSString though. I understand that there is no such thing as a constructor in Objective-C, so how might the following be accomplished without having to use stringFromCppString
-(void)something:(NSString*)someString
{
NSLog(@"%@", someString);
}
-(void)activity
{
std::string activityName = "Calculator";
[self something:[NSString stringFromCppString:activityName]];
}
In most cases, code making use of std::string can be separated from code using NSString. However, there is a fair amount of bridging that occurs, and the code becomes distracting with stringFromCppString all over the place.
std::string s = ""; NSString *nsstr = @(s.c_str());