如何将 const char * 连接到 NSString * [英] How to concat a const char * to a NSString *

查看:37
本文介绍了如何将 const char * 连接到 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 有效?谢谢!

Why stringByAppendingString fails but stringWithFormat works? Thanks!

推荐答案

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

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

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

As per understanding self.consoleText ---> nil so it will not appending string.

所以做类似的事情

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

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

这篇关于如何将 const char * 连接到 NSString *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆