Reputation: 7613
for eg.
NSMutableString * str1 = [[NSMutableString alloc]initwithString:@"matrix"];
NSMutableString * str2 = [str1 retain]; // str2 = matrix - output
NSMutableString * str3 = [str1 copy]; //str3 = matrix - output
what happen when 2nd line execute. are str1 and str2 different objects ? str1 points to "matrix", but is str2 also points to "matrix" ? if i change contents of str1, will str2 content changed ??
Upvotes: 0
Views: 869
Reputation: 410552
str1
and str2
are pointers that reference the same area of memory. Your memory layout looks roughly like this:
If you change where str1
points, e.g., by doing this
str1 = @"new string";
then str2
will still reference "matrix", but str1
will reference "new string":
Let's say, though, that str1
and str2
actually pointed to an instance of an NSMutableString
, and you did this instead:
[str2 setString:@"new string"];
Note, then, that str1
and str2
would still point the same object, so by modifying str2
, str1
would also change to "new string".
A shallow copy is a copy of an object in which its instance variables still point to the same memory location as the original object's ivars. A deep copy is a copy in which copies of the instance variables are also made.
Let's say you have a class, MyClass
, that has two instance variables, each of type NSString
. Here's a diagram of what the memory layout would roughly look like after a shallow and a deep copy:
Upvotes: 40
Reputation: 27601
what happen when 2nd line execute. are str1 and str2 different objects ?
No. They point to the same object, which now has a retain
count of 2. (init
increments this counter)
str1 points to "matrix", but is str2 also points to "matrix" ?
Yes.
if i change contents of str1, will str2 content changed ??
Yes.
Upvotes: 5