2015-11-05 60 views
0

我想在我可以寫這樣的方式來寫一個客觀-C++程序:目的-C++轉換的std :: string到的NSString

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

self.myLabel.text = thisWontWork->吧? –

+0

哦,是的,這是一個std :: string :) ..'self.myLabel.text = @(thisWontWork-> bar.c_str())' –

+0

你想複製字符串中的數據,還是你想要在沒有獲得所有權的情況下呈現C++字符串中的數據的NSString? –

回答

1

這應該工作:

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

它轉換std::stringconst char *NSString

但請注意:你正在泄漏foo,所以:

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

及用途:

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

你是什麼意思泄漏foo? – user235236

+1

@ user235236您正在調用'new',並且您從不會調用'delete'。 – trojanfoe