Ser Pounce
Ser Pounce

Reputation: 14571

"Copy" when using ARC

I know that when using ARC and you have an NSString property, you do @property(nonatomic, copy) just as you would MRC. But I'm wondering, after I converted my project to ARC, I still have this in my initializer method:

_someString = [someStringParameter copy]

Is this a bug? Or even with ARC, do I still need to explicitly say "copy" ? Or should I just do:

self.someString = someStringParameter

and all will be OK? Bit confused here...

Upvotes: 0

Views: 113

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

_someString = [someStringParameter copy];

Is this a bug?

No.

Or even with ARC, do I still need to explicitly say "copy" ?

Absolutely.

You're assigning the instance variable by copy and it's perfectly legit under ARC. As opposed to that, doing just:

_someString = someStringParamenter;

will cause ARC to automatically retain (not copy) it, resulting in something like

_someString = [someStringParameter retain];

This happens because under ARC variables have an implicit __strong identifier unless specified otherwise.


self.someString = someStringParameter

This is right, and both under ARC and MRC you'll get the object to be copied if you provided the copy attribute in the property declaration.

That said, it's still a bad idea to use accessor methods in initializers, since they may have unwanted side effects in case you have a custom implementation for them. Check out this answer on the subject: Should I refer to self.property in the init method with ARC?

Upvotes: 1

Tommy
Tommy

Reputation: 100652

You'd never use self.someString = anything in your initialiser. The dot notation is a method call. You shouldn't call methods on classes that aren't fully instantiated yet. Most demonstrable failure case: a subclass overrides setSomeString: — where is it in its init when that method is called?

ARC will handle proper retains and releases on instance variables but can't automatically do copies — e.g. there are __strong and __weak modifiers but no __copy. So you still need explicitly to copy when doing a direct instance variable assignment.

Upvotes: 2

Related Questions