tags:

views:

87

answers:

2

Hi,

I'm getting sublayers of a CALayer with this property accessor:

// @property(copy) NSArray *sublayers

NSArray* layer = mylayer.layer.sublayers;

Since this property uses "copy", every time I simply execute:

mylayer.layer.sublayers

is an entire copy of the sublayers array being made for me? If so that might be bad, because I could have one hundred+ layers, and definitely don't want to create a huge copy of them. I'm just looking to get a count and iterate through the existing layers, just a pointer to the existing layers,

Thank you

+2  A: 

When you use the 'copy' declaration and you @synthesize the property, then copy is used when the property is set.

In your example, you are only accessing the value which just gives you a pointer to the sublayers array.

Here's a link to the ADC documentation on this point.

Update

  1. IIRC, the runtime is smart enough to know if the object being set is mutable. If an immutable object is being passed in to the property it is retained and not copied.
  2. In some cases, if you are passing in a mutable object that you want to be able to modify, then you should write your own setter that calls mutableCopy on the object. This is shown in the documentation link that I provided.
Abizern
This is correct - the copying only happens when you assign to the property (or call setSublayers:), not when you use it.
Jesse Rusak
+1  A: 

I'm not sure I understand your answer Abizern so let me say this:

If you use (copy) on a property you will be making a whole new copy of that object so would be wasting a lot of memory. I'm not sure why they are doing that, they could just use (readonly) instead if they want to protect the values from change. Plus remember most value classes are immutable in Obj-C so they can't change the value anyway.

As I understood the OP's problem, he was worried that he was creating a copy of the sublayers array whenever he was accessing the property. I was trying to say that the copy is only used when setting the property. Getting the property just returns a pointer to the object.
Abizern
Ah, gotcha, thanks for the clarification.
The reason they're using `copy` is that they want to prevent modification to the array externally. If they were using 'retain' instead of 'copy', you could pass a NSMutableArray to setSublayers: and then change it behind the layer's back.
Jesse Rusak