0

If I declare a public property as :

@property (retain) NSString * name;

Then how does the compiler implicitly implement this? I have read that the retain gains ownership over the instance variable "_name". I have also read that "retain" message increases the reference count of the object. So each time I call the setter for "name" property in the above example, will it increase the reference count?

So after this,

object.name=@"name1";
object.name=@"name2";

Will the reference count be 2?

hcnimkar
  • 301
  • 2
  • 13
  • Possible duplicate http://stackoverflow.com/questions/2255861/property-and-retain-assign-copy-nonatomic-in-objective-c – Sujay Jun 04 '15 at 10:52

2 Answers2

0

According to Blamdarot in this answer:

"retain" is needed when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count) the object. You will need to release the object when you are finished with it.

Pang
  • 9,564
  • 146
  • 81
  • 122
Sujay
  • 2,510
  • 2
  • 27
  • 47
0

To answer your specific question:

object.name = @"name1";

name now holds a strong reference to the "name1" string instance.

object.name = @"name2";

name now holds a strong reference to the "name2" string instance. No object holds a reference to the "name1" instance, and a release statement will be inserted by the compiler for "name1". (in practice, the first statement will likely be optimized away entirely).

Aderstedt
  • 6,301
  • 5
  • 28
  • 44