gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:59:32 25 4
gpt4 key购买 nike

我想以这样的方式编写一个 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”

最佳答案

这应该有效:

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());

关于c++ - Objective-C++ 将 std::string 转换为 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33552304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com