Don't confuse NSString
which is immutable (can't be modified) with a constant string (i.e. @"A string").
object can be autoreleased or retained if the object it points to is not
a constant string.
For example, this will give you an autorelease / retainable NSString:
NSString *myStr = [NSString stringWithCString:"A string" encoding:NSMacOSRomanStringEncoding];
Then in main an NSString object is declared but the alloc message is sent to NSMutableString. Is this allowed?
With the code in the text:
NSString *myString = [NSMutableString stringWithString: @"A string"];
If you look up the class method stringWithString
you'll see it returns the id
Being a generic data type, it can be assigned to any object type. In this case NSString
. Since NSMutableStrings
must be mutable (modifiable) the constant string is copied instead of assigned as would happen if you called [NSString stringWithString:@"A string"]
***** Extra detail - This may be confusing - Sorry *****
The result is an NSMutableString
object that is statically typed as an NSString
. Since NSMutableString
is a child class of NSString
all the methods for an NSString
object work fine.
If you were to try call a method for an NSMutableString
object on myStr
the compiler would give you a warning that it may not respond since it is statically typed as an NSString
. At runtime the method can be called successfully since the object was created as an NSMutableString
. Statically typing it doesn't change that fact.
Try calling [myStr appendString:@" appended"];
and see what happens to myStr