How to concat a const char * to a NSString *

喜你入骨 提交于 2020-01-04 17:51:04

问题


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!


回答1:


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];
}



回答2:


NSString *original = @"Thinking";
const char *str = "...";
NSString *other = [NSString stringWithCString:str encoding:NSASCIIStringEncoding];
original = [original stringByAppendingString:other];
NSLog(@"original: %@", original); // original: Thinking...


来源:https://stackoverflow.com/questions/4827401/how-to-concat-a-const-char-to-a-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!