2

When I'm setting a property with an object that is currently in a retained NSArray, will it only store the pointer (light-weight), or will it copy the contents to the property?

From what I know, it seems like it would only assign the pointer, but I'm not sure.

Also, under what circumstances would using *pointer = *otherPointer or the set methods (setDelegate, for instance) copy the value, instead of just passing the pointer, if any. Shouldn't it always just pass the pointer address?

Matt
  • 22,721
  • 17
  • 71
  • 112
RileyE
  • 10,874
  • 13
  • 63
  • 106
  • I don't mean to sound snarky, but it depends upon how the `@property` is defined. If it's defined with `copy` it will copy it. If not, it won't. If I'm not understanding your question, let me know. As an aside, technically, the property is always getting a pointer (if it has the asterisk), but it's just a question of whether the pointer is pointing to the same thing, or a copy of that thing, and whether the object has its `retainCount` increased or not. – Rob Aug 11 '12 at 00:54
  • Yeah. So, it will only copy it if its a property with the 'copy' attribute? Ivars are strictly pointer translations as well? – RileyE Aug 11 '12 at 00:55
  • Re `copy` attribute, yes. Re ivars, not sure if I understand the question, but wherever you see the asterisk associated with some object var name, it's really just a pointer to something. – Rob Aug 11 '12 at 00:58

1 Answers1

3

It always passes the pointer, as you said. Unless you are specifically adding a de-referencing sign, this will always be the case.

However, when you add a property to a class, and set the setter to copy:

@property (nonatomic, copy) id obj;

When using the dot syntax or the setter, This will be translated to:

_obj = [otherObj copy];

Here, it will depend whether the object in question supports copying itself, or will it fall back to it's super class NSObject or another intermediate class's copy.

Moreover, Collection classes NSDictionary and NSArray do a shallow copy, as in they copy the references to their objects only, so you have two collections pointing to the same set of objects.

Mazyod
  • 22,319
  • 10
  • 92
  • 157
  • 1
    Well, copy is really for mutable objects. If you ask an array to copy itself, you get the original. if you ask a mutable array, you will get a new array with the objects of the original. Likewise with a string. Frankly, I don't use copy enough - its REALLY a good idea to use it for things that are often provided to you as mutable (even though the method may declare itself as returning a non mutable array, it can (and will) in some cases return a mutable one. Some of the OSX interfaces which declare -(NSString). If in doubt use "copy" and it gives protection while have virtually no cost. – David H Aug 11 '12 at 01:21
  • Unless if the copied array is massive, right? Maybe a large image array, or whatnot. Its an outlier, but its something you would want to avoid. – RileyE Aug 11 '12 at 04:30