简体   繁体   中英

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 ??

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

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:

替代文字

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM