I have some Objective-C++ code like this:
// header
@interface MyObjcClass
- (void) myMethod: (NSString *) text;
@end
// implementation
@implementation MyObjcClass
- (void) myMethod: (NSString *) text
{
someInternalObject->useWstring(nsStringToWstring(text))
}
std::wstring nsStringToWstring(const NSString * text)
{
NSData * data = [text dataUsingEncoding: NSUTF32LittleEndianStringEncoding];
// and then some other stuff irrelevant to this question
return std::wstring(pointerToNewString, pointerToNewString + stringLength);
}
@end
Straightforward so far; seems fine to me. And works great when called from Objective-C and Objective-C++ code! However, when Swift gets involved...
func mySwiftFunc(text: String) {
myObjcClassInstance.myMethod(text)
}
This also seems straightforward. The compiler's translation layer automatically bridge's Swift's String
to Objective-C++'s NSString *
. Unfortunately, that's false... it seems to bridge it to something called _SwiftValue
. And then that's passed in and I try to call dataUsingEncoding:
on it, but apparently _SwiftValue
doesn't have such a selector, so I get this crash:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue dataUsingEncoding:]: unrecognized selector sent to instance 0x7f9ca7d63ee0'
I'm at a loss for how to resolve this. I can't use NSString
in Swift and just pass that down because the compiler requires that I pass a Swift String
.
Is there any way to resolve this?
Any of these solutions will do:
- Force generated Swift header to accept a
NSString *
instead of aString
- A way to turn a
_SwiftValue
into data from within Objective-C++ - Any flags that let the compiler or runtime know to translate that
_SwiftValue
to aNSString *
before trying to message it - etc.
Environment
- The ObjC++ code is within a modular framework that is referenced by the Swift code; they're not compiled together.
- The ObjC++ module is compiled with Xcode 8.3.3 and the Swift code with 9.2.
- There may be other discrepancies; there are lots of moving parts in these projects.