Objective-C:如何将字符串附加到NSMutableString? [英] Objective-C: How do you append a string to an NSMutableString?

查看:87
本文介绍了Objective-C:如何将字符串附加到NSMutableString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

URL下载

http://code. google.com/p/mwiphonesdk/source/browse/#svn/trunk/iMADE/PrepTasks/08

我在上面链接的位置上有代码,并且我正在使用 NSMutableString 在下载数据时附加字符串.但是我发现使用appendString不会增加可变字符串的长度.我一定做错了.

I have code at the location at the link above and I am using NSMutableString to append strings as data is downloaded. But I am finding that using appendString does not increase the length of the mutable string. I must be doing something wrong.

完成后,我需要将 NSMutableString 转换为 NSString 以返回它.我一直在寻找可以做到这一点的例子,但是我还没有看到.

And when I am done I need to convert NSMutableString to NSString to return it. I have looked for examples to do this but I do not see any yet.

我最熟悉Java和C#,这里有一个StringBuffer/StringBuilder,它允许您追加片段,它们只需在末尾调用toString即可获取String.在Objective-C中似乎并不那么容易.

I am most familiar with Java and C# where there is a StringBuffer/StringBuilder which allows you to append pieces and them simply call toString at the end to get a String. It does not appear to be this easy in Objective-C.

NSString* str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

#pragma mark TODO Confirm this is appending a value to the mutable string
[self.mutableString appendString:str];

NSLog(@"str length: %d, %d", [str length], [self.mutableString length]);

上面是调用appendString的代码部分.

Above is the section of code that calls appendString.

我看到str的长度> 0,但是调用appendString不会增加self.mutableString的长度.

I see that str has a length > 0 but calling appendString does not increase the length of self.mutableString.

我在做什么错了?

推荐答案

对于具有NSMutableString*并需要返回NSString*的情况,前者是后者的子类,因此在任何地方看到NSString* NSMutableString*就足够了.

As for having an NSMutableString* and needing to return an NSString*, the former is a subclass of the latter so anywhere you see an NSString* an NSMutableString* will suffice as-is.

从您发布的内容来看,您的代码看起来还可以.我唯一能想到的是,初始化str变量时可能没有任何数据要说.在这种情况下,添加空字符串对mutableString无效.

Your code looks OK from what you've posted. The only thing I can think of is that perhaps there isn't any data to speak of when initializing the str variable. In such a case appending an empty string will do nothing to mutableString.

您还需要确保已正确分配和初始化self.mutableString.您可以将邮件发送到nilNSObject*,当[self.mutableString length]返回0时,这可能会产生误导.

You'll also want to make sure self.mutableString has been properly allocated and initialized. You can send messages to NSObject*s that are nil which may be misleading when [self.mutableString length] returns 0.

这篇关于Objective-C:如何将字符串附加到NSMutableString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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