Objective-C++ 将 std::string 转换为 NSString

Objective-C++ converting std::string to NSString

我想以这样的方式编写一个 objective-C++ 程序:

class foo
{
public:
foo()
{
    bar = "Hello world";
}
std::string bar;
};

然后(在同一个 .mm 文件中)我可以创建一个 class 的实例,然后执行类似的操作:

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *myLabel;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    foo* thisWontWork = new foo();
    self.myLabel.text = foo.bar; //this doesn't work obviously

// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

这会有效地将标签 'myLabel' 的文本更改为 "Hello world"

这应该有效:

self.myLabel.text = @(foo->bar.c_str());

std::string 转换为 const char *NSString

但请注意:您正在泄漏 foo,所以:

@interface ViewController ()
{
    foo _foo;
}
@property (weak, nonatomic) IBOutlet UILabel *myLabel;
@end

并使用:

self.myLabel.text = @(_foo.bar.c_str());