Reputation: 51911
Trying to append const char *str
to a NSSting *
:
In .h
@interface SomeViewController : UIViewController
{
NSString *consoleText;
}
@property (nonatomic, retain) NSString *consoleText;
@end
In .mm
@synthesize consoleText;
The following is OK:
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
fails but stringWithFormat
works? Thanks!
Upvotes: 2
Views: 3375
Reputation: 38012
NSString *original = @"Thinking";
const char *str = "...";
NSString *other = [NSString stringWithCString:str encoding:NSASCIIStringEncoding];
original = [original stringByAppendingString:other];
NSLog(@"original: %@", original); // original: Thinking...
Upvotes: 1
Reputation: 2515
In two of the operations you are doing different things one is appending existing string and another you are setting a new string
To append string there should be a string object
self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]];
As per understanding self.consoleText ---> nil so it will not appending string.
so do something like
if(self.consoleText)
{
self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]];
}else
{
self.consoleText = [NSString stringWithUTF8String:str];
}
Upvotes: 1