Actually, whether you use the 1st or 2nd option has nothing to do with the array itself.
The 2nd option would not result in any change even if the array was mutable and you replaced the object at index 1. string
would still point to the original object.
In the example you've given, the choice of the two options only matters if in reality, the string you get from the array is an NSMutableString
. If the string is an immutable NSString
then either option gives the same result. But if you actually have a mutable NSMutableString
, then option 2 means that your string
value can change over time of another reference to the mutable string makes changes to the string.
Example:
NSMutableString *mutable = [NSMutableString stringWithString:@"hello"];
NSArray *array = @[ @"stuff", mutable ];
NSString *string1 = [NSString stringWithString:array[1]];
NSString *string2 = array[1];
NSLog(@"string1 = %@, string2 = %@", string1, string2);
[mutable appendString:@" there"];
NSLog(@"string1 = %@, string2 = %@", string1, string2);
The log output will be:
string1 = hello, string2 = hello
string1 = hello, string2 = hello there
See how string2
was changed as a result of modifying mutable
.