Search code examples
objective-cmemory-managementinstance-variablesdeclared-property

Is the object retained when setting a property's ivar directly in -init?


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.


Solution

  • 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].)