开发者

Objective-C: How do you append a string to an NSMutableString?

URL Download

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

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.

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.

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

Above is the section of code that calls appendString.

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

What am I doing wrong here?


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.

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.

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.


I have fixed the problem. I simply was not initializing the NSMutableString value and it was transparently not doing anything.

Before appending the string I put the following code.

if (_mutableString == nil){
    _mutableString = [[NSMutableString alloc] init];
}

Thanks everyone for answering. And it is good to know that I can use NSMutableString in place of NSString. (that is too easy) :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜