Matrix
Matrix

Reputation: 7613

retain in Objective C

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

Answers (2)

mipadi
mipadi

Reputation: 410552

str1 and str2 are pointers that reference the same area of memory. Your memory layout looks roughly like this: alt text

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": alt text

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".

Shallow copy vs. deep copy

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:

alt text

Upvotes: 40

Shaggy Frog
Shaggy Frog

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

Related Questions