user235236
user235236

Reputation: 467

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

I would like to write an objective-C++ program in such a way that I could write:

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

Then (below in the same .mm file) I could create an instance of that class then do something like:

@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

which would effectively change the text of label 'myLabel' to "Hello world"

Upvotes: 0

Views: 1181

Answers (1)

trojanfoe
trojanfoe

Reputation: 122381

This should work:

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

Which converts std::string to const char * to NSString.

But note: you are leaking foo, so:

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

and use:

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

Upvotes: 1

Related Questions