0

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"

4
  • self.myLabel.text = thisWontWork->bar ? Commented Nov 5, 2015 at 18:42
  • oh, yeah that is a std::string :).. self.myLabel.text = @(thisWontWork->bar.c_str()) Commented Nov 5, 2015 at 19:13
  • do you want to copy the data in the string, or do you want an NSString that presents the data in the c++ string without taking ownership? Commented Nov 5, 2015 at 20:04
  • If theres another way that the below answer didn't cover I would be happy to see it! Commented Nov 5, 2015 at 23:31

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean leaking foo?
@user235236 You are calling new and you never call delete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.