This question already has an answer here:
what is actual difference between NSString and NSMutable String in Objective-C? I have searched a lot but not getting any answer..I understand that NSString is Immutable object and NSMutableString is Mutable object but I want to understand the difference between them with the help of an example..Please help me..
now question has solved..
Difference between NSMutableString and NSString:
NSMutableString: NSMutableString objects provide methods to modify the underlying array of characters they represent, while NSString does not. NSMutableString exposes methods such as appendString, deleteCharactersInRange, insertString, replaceOccurencesWithString, etc. All these methods operate on the string as it exists in memory.
NSString: It is a create-once-then-read-only string if you will; you'll find that all of its "manipulation" methods (substring, uppercaseString, etc) return other NSString objects and never actually modify the existing string in memory.
Example :
Both of these, functionally, do the same thing except but - the top code block leaks.
generates a new immutable NSString object which you then tell the pointer to point to. In the process, however, you orphan the NSString object that it originally pointed to.
In Objective C, two types of string Objects are there one is mutable and Immutable.
To create an immutable string we use
NSString
and to create a mutable string we useNSMutableString
.If we are creating a string object using
NSString
, it is an immutable string object. This means the string cannot subsequently be modified in any way. (although any NSString pointer can be reassigned to a new NSString object.)For Mutable strings, we use
NSMutableString
, which is a subclass ofNSString
.To assign a mutable string object:
or
Immutable String.....
replace the second string
And list their current values
Mutable strings
Setup two variables to point to the same string
Replace the second string
// And list their current values
Notice when you use the immutable string class that the only way to
replace
a string is to create a new string and update your variablestr2
to point to it.This however doesn't affect what str1 is pointing to, so it will still reference the original string.
In the
NSMutableString
example, we don't create a second string, but instead alter the contents of the existingHello Testing
string. Since both variables continue to point to the same string object, they will both report the new value in the call toNSLog
.It is important to differentiate between a pointer variable and the actual object it points to. A
NSString
object is immutable, but that doesn't stop you from changing the value of a variable which points to a string.