Reputation: 15296
Please check the below code, where I am creating multiple reference for an array
NSMutableArray *array1 = [[NSMutableArray alloc] init];
NSMutableArray *array2 = array1;
[array1 addObject:@"One"];
[array1 addObject:@"Two"];
NSLog (@"Array1 %@",array1);
NSLog (@"Array2 %@",array2);
Console output is
Array1 ( One, Two ) Array2 ( One, Two )
Both Array1 and Array2 reference to same address
Like wise I tried for NSMutableString, I didn't work out
NSMutableString *str1 = [[NSMutableString alloc] init];
NSMutableString *str2 = str1;
str1 = @"Hello";
NSLog (@"Str1 : %@", str1);
NSLog (@"Str2 : %@", str2);
Console Output is Str1 Hello Str2 (null)
Is there any way to have reference to string ?
Upvotes: 0
Views: 48
Reputation:
Everything is quite normal. With :
str1 = @"Hello";
str1
doesn't point to the memory you allocated two lines above anymore. str2
didn't change and still point to that memory place.
The example you gave doesn't looks the same for arrays and string. In the first you add objects to one array, but don't change the value of any pointer.
In the second you are modifiying the reference to an object.
The second example, should be written as something like :
NSMutableString *str1 = [[NSMutableString alloc] init];
NSMutableString *str2 = str1;
[str1 appendString:@"foo"];
NSLog (@"Str1 : %@", str1);
NSLog (@"Str2 : %@", str2);
Output :
Str1 : foo
Str2 : foo
Given two references on the same mutable string (one memory place), and using NSMutableString
's method, both references will be modified.
Upvotes: 2