iOS copy Summary

copy and mutableCopy Conclusions first, then code. - copy: For a mutable object, calling returns a new immutable object, while the retain count of the original mutable object remains unchanged. For an immutable object, calling returns the original immutable object, and the retain count of that immutable object is incremented by one (equivalent to ). - mutableCopy: Regardless of whether the object is mutable or immutable, calling always returns a new mutable object, and the retain count of the original object remains unchanged. Output: Extended notes: Assigning between mutable and immutable objects can cause problems: Of course, in assignment operations, no new objects are created and the retain count of all objects increases by one. copy and strong in property declarations First, one point must be clear: the modifier in a property declaration and the method call on an object are different concepts. The modifier in a property declaration means that the auto-generated setter will perform a copy operation on the incoming object. The addresses in the output are actually unchanged! This is understandable: and need no explanation. The in the setter does perform a copy, but as discussed in the previous section, copying an immutable object does not produce a new object. Of course, if you use directly, the situation is the same as in the previous section. Note: when you override the setter for a -modified property, you also need to perform a copy on the incoming parameter. One more point, the following code: Output: The reason addresses match is that the system performs an optimization: as long as the string content is the same, no new memory will be allocated. Additionally, for the class , 64-bit systems introduced the Tagged Pointer mechanism. For details, see here and here.