@property privateItems - why not (copy)?


Hello there,

I might be missing something, but according to the chapter 3:

then why there’s no copy keyword used in property definitions described in the 8th chapter?

[code]@property (nonatomic, readonly) NSArray *allItems;

@property (nonatomic) NSMutableArray *privateItems;[/code]

I assume it’s not used for the *allItems property to avoid the process copying it, as it’d need to be converted from NSMutableArray to NSArray. Why there’s not copy on the *privateItems, though?

On the other hand, if both of them actually are to be declared as strong references, shouldn’t it be explicitly stated? Once again, chapter 3:


I am not sure if you already got an answer for this but I think BNR updated the this portion of the book in later printing.

My book (second printing of 4th edition) defined the allItems property in following manner:
@property (nonatomic, readonly, copy) NSArray *allItems;

The second property is same as what you wrote and I think this is correct. It does not need copy attribute.
I think your reasoning regarding when to use copy attribute is backward. The first property need copy attribute where second does not.

My understanding of copy attribute is to avoid the immutable array gets changed to by caller when immutable data type has mutable subclass type.
Since NSMutableArray is a (i.e inherit from) NSArray, it is possible that caller create the NSMutableArray object reference and points to
the exact same data that NSArray is pointing, hence, possibly mutate the original array.
By giving copy property attribute, accessor will return the “copy” of NSArray not actual original NSArray.
Hence, even if caller does above operation in its routine, all it can change is the the “copy” not “original” Hence, data is safe.

I think this is well discussed in ch3 of book and you should read again. The book (obviously) explained better than me :slight_smile: so you really need to check it out.

As far as regarding with strong attribute, I also felt book’s style is not consistent on whether explicitly stating this attribute or not.
Nonetherless, it is still valid since strong is default. I think it is just matter of style.