NSMutableString Append Fails

I have an NSString that I'd like to append a { at the beginning of it.

 NSMutableString *str = [[NSMutableString alloc] initWithString:@"{"];
    [str stringByAppendingString:extracted];

This returns str with only {. Why is that? Objective-C is VERY frustrating with how it provides many ways of doing the same thing, yet for situations a different way is required.

I tried doing [NSMutableString string] and appending { then extracted and it still does not work. Why is this not working and what should I do?

Answers


stringByAppendingString returns a new string, it does not modify the old string.

All functions that begins with stringWith or arrayWith etc. create new objects rather than modifying old objects.

To acheive what you want, a simpler solution is:

 NSString *str = [NSString stringWithFormat:@"{%@", oldString];

or:

 NSMutableString *str = [@"{" mutableCopy];
 [str appendString:blah];

You are calling an NSString method that returns a new string and does not modify the string that it is called on. You need to call appendString.

[str appendString:extracted];

// use it like this

NSString *extracted = @"this is my string";
NSString *str = [[NSString alloc] initWithString:@"{"];
str =  [str stringByAppendingString:extracted];

Hope this will help you


Need Your Help

Customize/remove Django select box blank option

python django django-models django-forms

I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one optio...

Always save specific file type in windows to one location?

windows vb.net visual-studio-2010 registry

I'm trying to do the following I'm not sure if it's possible using VB.NET.