如何将const char *连接到NSString *

时间:2011-01-28 10:54:39

标签: iphone objective-c nsstring

尝试将const char *str附加到NSSting *

在.h

@interface SomeViewController : UIViewController
{
    NSString    *consoleText;
}

@property (nonatomic, retain) NSString *consoleText;

@end

在.mm

@synthesize consoleText;

以下是可以的:

const char *str = "abc";

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

但是以下失败了:

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

为什么stringByAppendingString失败但stringWithFormat有效?谢谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

在其中两个操作中,您正在执行不同的操作,一个是追加现有字符串,另一个是设置新字符串

要附加字符串,应该有一个字符串对象

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

根据理解self.consoleText --->没有,所以它不会附加字符串。

这样做

if(self.consoleText)
{
    self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]];

}else
{
self.consoleText = [NSString stringWithUTF8String:str];
}