Difference between stringByAppendingString and appendString in ios

1.9k views Asked by At

What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

2

There are 2 answers

3
luk2302 On BEST ANSWER

appendString: is from NSMutableString, stringByAppendingString: is from NSString.

The first one mutates the existing NSMutableString.

Adds to the end of the receiver the characters of a given string.

The second one returns a new NSString which is a concatenation of the receiver and the parameter.

Returns a new string made by appending a given string to the receiver.

The reason for that is that the regular NSStringis immutable and you cannot directly append something to it. The NSMutableString however as the name suggests is mutable and therefore can be modified.

0
Paulw11 On

The documentation for stringByAppendingString states that it

Returns a new string made by appending a given string to the receiver

so it doesn't modify the existing string - it can't, because as you noted, NSString is immutable

appendString, on the other hand, is a mutating method of NSMutableString which modifies the receiving NSMutableString.