我想以这样的方式编写一个Objective-C ++程序:
class foo
{
public:
foo()
{
bar = "Hello world";
}
std::string bar;
};
然后(在同一个.mm文件下面)我可以创建该类的实例然后执行以下操作:
@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”
答案 0 :(得分:1)
这应该有效:
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());