3

I try to understand when I need use copy? I thought that copy allocate new memory, but it doesn't. So, for example:

NSArray *array = @[@"111", @"111"];
NSArray *array1 = array.copy;
NSMutableArray *array2 = array.copy;
NSMutableArray *array3 = array.mutableCopy;
NSArray *array4 = array.mutableCopy;

New memory allocated only for array3 and array4. So, I can do for array1 and array2 simply:

NSArray *array1 = array;
NSMutableArray *array2 = array;

When I can use copy, it is only make immutable array2, when it will be helpfull for me?

4

2 回答 2

8

In Cocoa, the copy method can be very smart: if an object is immutable, it could return itself without making a copy, because there is no point in copying objects that cannot be changed. In your example, NSArray is immutable, and NSMutableArray is mutable. That is why only mutable objects make actual copying. Of course all mutable copies must allocate new memory, too.

于 2013-03-30T21:21:50.133 回答
0

There is a difference between:

NSArray *array1 = array.copy;

and

NSArray *array1 = array;

In the first case, the retain count of array is increased. In the second it is not. So if you ever release array, array1 may become invalid in the second case, while it will still be valid in the first one.

Exact consequences may depend of you using ARC or manual reference counting.

Mutable objects will be copied no matter what, so that you can modify the original without affecting the copy. This is unnecessary for immutable objects, as they can't be modified.

于 2013-03-30T21:29:31.373 回答