-1

What's the typical use-case of the copy properties' attribute?

When should I copy some value instead of just incrementing reference count as it can be achieved via the strong property?

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • 1
    Put a two `NSMutableString` property to an object, one `copy`, one `strong`. Do `NSMutableString *string = [[NSMutableString alloc] initWithString:@"Hello "];` and set it to both the property of your object. Logs the two properties. Then do `[string appendString:@"World"];`, log again the two properties. You'll see. Do the same and look at the objects addresses. – Larme Feb 24 '16 at 16:20
  • A good rule of thumb is: if the property is a pointer to a class which adopts the `NSCopying` protocol, the property should have the `copy` attribute unless you have a really good reason why it shouldn't. – Ken Thomases Feb 24 '16 at 18:57

1 Answers1

1

Others have answered this before, so I'll just point you to a couple of them.

First, the Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html, search for "Copy Properties Maintain Their Own Copies"

Here is a pretty good explanation of the various property attributes: Objective-C declared @property attributes (nonatomic, copy, strong, weak)

This answer does a good job of explaining a pretty typical use case and why you'd use copy: NSMutableString as retain/copy

Neither, however, mentions block properties, and you never want to use anything other than copy for blocks (assuming, of course, that you're using ARC, and ARC even handles this for you automatically):

Note: You should specify copy as the property attribute, because a block needs to be copied to keep track of its captured state outside of the original scope. This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically, but it’s best practice for the property attribute to show the resultant behavior. For more information, see Blocks Programming Topics.

From here: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html

Community
  • 1
  • 1
fullofsquirrels
  • 1,828
  • 11
  • 16
  • Actually, you doesn't need explicitly copy blocks under ARC. This mentioned even in provided quote from documentation: "This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically" – Borys Verebskyi Feb 24 '16 at 16:56
  • Fair point. I personally like to be explicit about certain things (including), but it's by no means required. I suppose my comment *should* have read "You never want to use anything *other* than `copy` for blocks, but you don't need to explicitly specify it". Thanks for the clarification, I've edited my comment accordingly. – fullofsquirrels Feb 24 '16 at 18:19