For many beginners, it is found that when modifying objects of the NSString type, there is this confusion. Why do some people use strong to decorate, and some people use copy to decorate?
Here's an example. First, declare 2 properties:
@property (nonatomic,copy) nsstring *copyname; @property (nonatomic,strong) NSString * STRONGNAME;
1.1. Create a mutable string that changes after the facet is changed.
nsmutablestring* mutablename = [nsmutablestring stringwithformat:@ "abc"];
1.2. Assigning Mutablename to attributes
Self. Copyname =mutablename;self. StrongName = Mutablename;
1.3. Print the results:
NSLog (@ "before the change. Copyname=%@\nstrongname=%@ ", self. Copyname,self. StrongName); NSLog (@ "%p,%p,%p", mutablename,self. Copyname,self. StrongName);
The printing results are as follows:
Before the change. COPYNAME=ABC strongname=abc0x7fdc32d346a0,0xa000000006362613,0x7fdc32d346a0
Discover that the copy decoration is actually a deep copy, copying a new space, the same content is stored in it.
1.4. Change the value of the Mutablename, and then print the results
[Mutablename appendstring:@ "def"]; NSLog (@ "After the change. Copyname=%@\nstrongname=%@ ", self. Copyname,self. StrongName);
The results are as follows:
After the change. COPYNAME=ABC Strongname=abcdef
The result is not difficult to explain. The strong decorated strongname and mutablename point to the same piece of space, and when you change the contents of the Mutablename point, the value obtained by StrongName will of course change. While the copy-modified Copyname points to another space, it has no effect when changing what mutablename points to.
2.1 Create an immutable string and assign a value to 2 properties
NSString *name [email protected] "ABC"; Self. Copyname =name; Self. StrongName = name;
2.2 Printing Results
NSLog (@ "before the change. Copyname=%@\nstrongname=%@ ", self. Copyname,self. StrongName); NSLog (@ "%p,%p,%p", name,self. Copyname,self. StrongName);
The results are as follows:
Before the change. COPYNAME=ABC STRONGNAME=ABC
0x10695e0f0,0x10695e0f0,0x10695e0f0
Found this time the result is a bit different from the last time, this copy is actually a shallow copy, just copy the address, and did not open up new space.
So when a property points to an immutable string object, there is no difference between the copy and strong adornments.
When a property points to a variable mutablestring type, you expect the property to change with the value of the mutablestring, using strong instead of copy. Array, the same as the dictionary. In fact, this involves the security of the data.
IOS about nsstring Types of properties Why sometimes use copy, sometimes with strong?