62

When not compiling with ARC, it is recommended to use copy properties for data types such as NSString. I could not find proper documentation on the use of copy in ARC mode. Can someone tell me what's applicable for ARC?

jscs
  • 63,694
  • 13
  • 151
  • 195
rustylepord
  • 5,681
  • 6
  • 36
  • 49
  • What are you trying to do? Show an example piece of code where you want to know the proper method to follow. – Dustin Jun 28 '12 at 17:15

4 Answers4

82

It is still recommended to copy because you want to avoid something passing a mutable string and then changing it without you knowing. A copy guarantees that the string you have will not change.

Joe
  • 56,979
  • 9
  • 128
  • 135
  • 9
    Note that when I say "guarantee" I am referring to code that conforms to Objective-C best practices. I can't account for a rogue programmer who thinks it is smart to add `copy` method to an `NSString` category for example. – Joe Jun 28 '12 at 17:26
  • what about `NSMutableArray` should I use copy for it. – Amit Battan Jul 16 '14 at 04:56
  • If you have an `NSMutableArray` that you want to be modified outside of your class then no, otherwise return a `mutableCopy` they can modify independently of your class. – Joe Jul 16 '14 at 12:28
14

Copying and ARC are orthogonal: you make copies of mutable objects to "freeze" their state; ARC keeps track of object's reference count.

NSString objects may or may not be mutable. When you receive an NSString* as a parameter, you cannot be certain that it is immutable unless you check its type (and even then you may get false positives). If your algorithm relies on the string not changing after being set, making a copy is the right thing to do. ARC, on the other hand, will ensure that the object is not released while you are holding a strong reference to it.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
12

It doesn't matter if you're using ARC or non-ARC.

The reasoning behind the copy is so that you can guarantee that your class' internal state can't be modified from outside the implementation.

This could happen if someone passes you an NSMutableString, and then modifies it later. That consideration is independent of the memory management environment.

Mihir Oza
  • 2,768
  • 3
  • 35
  • 61
Matt Wilding
  • 20,115
  • 3
  • 67
  • 95
11

copy counts as strong. Use:

@property(nonatomic,copy) NSString *name;

https://devforums.apple.com/message/654033#654033

or even:

@property NSString *firstName;

http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW7

Snowcrash
  • 80,579
  • 89
  • 266
  • 376