【问题标题】:How to concat a const char * to a NSString *如何将 const char * 连接到 NSString *
【发布时间】:2011-01-28 10:54:39
【问题描述】:

尝试将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 有效?谢谢!

【问题讨论】:

  • 你所说的“失败”是什么意思?碰撞 ?字符串不好?
  • @sloonz 字符串没有连接。

标签: iphone objective-c nsstring


【解决方案1】:

在两个操作中,您正在做不同的事情,一个是附加现有字符串,另一个是设置新字符串

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

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

根据对 self.consoleText 的理解 ---> nil 所以它不会附加字符串。

所以做类似的事情

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

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

【讨论】:

  • 添加初始化后效果很好:self.consoleText = @"";
  • 如果你在控制台中调试,你可以用“p”代替“po”,它也可以完成这项工作。
【解决方案2】:
NSString *original = @"Thinking";
const char *str = "...";
NSString *other = [NSString stringWithCString:str encoding:NSASCIIStringEncoding];
original = [original stringByAppendingString:other];
NSLog(@"original: %@", original); // original: Thinking...

【讨论】:

  • 对不起,刚刚意识到并切换了它。我想我需要更频繁地查看文档。
  • 你也可以NSString *other = [original stringByAppendingFormat:@"%s", str];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多