How to execute const char * in NSString *

Trying to add const char *str to NSSting * :

In .h

 @interface SomeViewController : UIViewController { NSString *consoleText; } @property (nonatomic, retain) NSString *consoleText; @end 

In .mm

 @synthesize consoleText; 

In order:

 const char *str = "abc"; self.consoleText = [NSString stringWithFormat: @"%@%@", self.consoleText, [NSString stringWithUTF8String:str]]; 

but the following failed:

 self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]]; 

Why stringByAppendingString work, but stringWithFormat works? Thanks!

+1
source share
2 answers

In two operations that you do different, an existing row is added, and the other you set a new row

To add a string, there must be a string object

 self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]]; 

According to the understanding of self.consoleText ---> nil, so it will not add a line.

do something like

 if(self.consoleText) { self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]]; }else { self.consoleText = [NSString stringWithUTF8String:str]; } 
+1
source
 NSString *original = @"Thinking"; const char *str = "..."; NSString *other = [NSString stringWithCString:str encoding:NSASCIIStringEncoding]; original = [original stringByAppendingString:other]; NSLog(@"original: %@", original); // original: Thinking... 
+1
source

All Articles