The first thing to mention here is the copy in the attribute list where the attribute is defined
@property (nonatomic,copy) NSString *name;
Here I define a person class, which is no longer stated here
Here is the code
Person *p = [[Person alloc] init];
nsmutablestring *s = [[Nsmutablestring alloc] initwithformat:@ "123"];
P.name = s; At this point, the value of name is @ "123"
NSLog (@ "**%@", p.name);
[s appendstring:@ "World"];
NSLog (@ "%@", p.name);
NSLog (@ "%p---%p", s,p.name);
Output Result:
**123
123
0x100206e00---0x100206cf0
you can see that the value of the mutable string is assigned to the property name, but the address changed, after the first output 123 I re-assigned to the world, but did not affect the value of the P.name, which verifies that the address is indeed different. In fact it's internally through
-(void) SetName: (nsmutablestring *) name
{
if (_name! = name) {//To determine if a value needs to be re-assigned
[_name release]; Release old reference, counter-1
_name = [name copy]; Re-assign the value, use copy******** is here *********
}
}
A deep copy was made. Since S is a mutable array, copy will open a new address space. If S is an immutable group, then a shallow copy is performed
If you change the code to:
Person *p = [[Person alloc] init];
NSString *s = @ "123";
P.name = s; At this point, the value of name is @ "123"
NSLog (@ "%@", p.name);
NSLog (@ "%p---%p", s,p.name);
Output Result:
123
0x100001068---0x100001068
The address is the same, stating that a shallow copy
Summarize:
Copy:Shallow copy: Does not produce a new object, directly pointing to the original object (the same address data, although the name of the pointer is different) Copy the result is an immutable object, and its acceptance type is not related to its incoming type is not related
mutablecopy:Deep copy: Produces a new object whose contents are the contents of the original object, the result of which is a mutable object, which has no relation to its incoming type, but is affected by its receive type.
Copy : Copied is variable, then deep, otherwise shallow
NSString *s2 = [S1 copy];//Eight cases (S1: mutablestring/string;s2:mutablestring/string; copy/mutablecopy), only the S1 is immutable and the Copy method is used to satisfy the shallow copy while the rest is a deep copy
When using Nscopy to copy an immutable object, its behavior is shallow copy, the rest is deep copy//When using nsmutablecopy, it is a deep copy
So why does the shallow copy address not change?
when the type of the copy is a string constant (that is, an immutable string), the system optimizes for us, declares multiple strings,but all are constants, and the content is equal, then the system only applies a space for us. Assignment process: input data → register processing → open memory → write data. A deep copy, you can get a copy of the object pointer, and perform an assignment operation.
Copy of Objective-c (duplicate)