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..
Immutable String.....
NSString *str1 = @"Hello Testing";
NSString *str2 = str1;
replace the second string
str2 = @"Hello hehehe";
And list their current values
NSLog(@"str1 = %@, str2 = %@", str1, str2);
//logs as below
//str1 = Hello Testing, str2 = Hello hehehe
Mutable strings
Setup two variables to point to the same string
NSMutableString * str1 = [NSMutableString stringWithString:@"Hello Testing"];
NSMutableString * str2 = str1;
Replace the second string
[str2 setString:@"Hello ikilimnik"];
// And list their current values
NSLog(@"str1 = %@, str2 = %@", str1, str2);
//logs as below
//str1 = Hello ikilimnik, str2 = Hello ikilimnik
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 variable str2
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 existing Hello Testing
string. Since both variables continue to point to the same string object, they will both report the new value in the call to NSLog
.
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.