0

My understanding is that instance variables should be accessed directly from inside the init method. For example:

@interface ABC : NSObject

     @property (strong, nonatomic) NSString *name;

@end

@implementation ABC

- (id)init
{
    if ((self = [super init]) != nil)
    {
        _name = @"some name";
    }
}

// another init example

- (id)initWithName:(NSString*)n
{
    if ((self = [super init]) != nil)
    {
         _name = n;
    }
}

@end

I am wondering about the _name variable. In both init examples, is _name retained? For this example, I am using ARC.

applegal
  • 25
  • 1
  • 5

1 Answers1

1

Whether _name is retained in this code depends on whether you have ARC turned on. If you do, ARC will retain the object for you (since that is ARC's job). If you don't have ARC turned on, you need to retain it yourself, which would look like:

- (id)initWithName:(NSString*)n
{
    if ((self = [super init]) != nil)
    {
         _name = [n retain];
    }
}

(It's also worth pointing out that NSStrings should usually be copied rather than retained, so you would make the property @property (copy, nonatomic) NSString *name; and the assignment would be _name = [n copy].)

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • I am using ARC (updated my question). So even in the case of _name = @"some name"; ARC would handle the retain? Also, good point on changing it to copy… Thank you for your quick response. – applegal Apr 16 '14 at 19:48
  • @applegal: Yep, that's exactly what ARC is for. It understands Objective-C's ownership model (e.g. "If I'm assigning an object I didn't allocate to a strong variable, it needs to be retained") and it silently inserts retains where they're needed to follow the rules. – Chuck Apr 16 '14 at 20:02