57

It is my understanding that setting an ivar now retains the object being assigned to it, since setting variables defaults to the strong qualifier. Because ivars are in the scope of the object they are declared in and strong retains objects within the scope of the variable, this means the ivars value would never be released while the object containing the ivar is still alive.

Is this correct?

If so, am I right in thinking that there is, in terms of memory management, no difference between a retaining (strong) property and a simple ivar anymore?

Toastor
  • 8,980
  • 4
  • 50
  • 82

2 Answers2

71

If a variable:

  1. Is declared in a class using ARC.
  2. Is used solely for class implementation (not exposed as part of the class interface).
  3. Does not require any KVO.
  4. Does not require any custom getter/setter.

Then it is appropriate to declare it as an ivar without a corresponding @property/@synthesize, and to refer to it directly within the implementation. It is inline with Encapsulation to declare this ivar in the class implementation file.

// MyClass.h
@interface MyClass : ParentClass
@end

// MyClass.m
@implementation MyClass {
    NSString *myString;
}

- (void)myMethod {
    myString = @"I'm setting my ivar directly";
}
@end
  • This ivar will be treated as __strong by the ARC compiler.
  • It will be initialized to nil if it is an object, or 0 if it is a primitive.
bearMountain
  • 3,950
  • 1
  • 36
  • 44
  • Can't be sure about 2 item. U can access public ivar using classInstance->iVar = @"New value" – Denis Mikhaylov Dec 01 '11 at 05:17
  • 2
    @DenisMikhaylov Good point. Though I think I'll leave in "point 2" because I'm talking about best practice, and it's probably not good practice to access a class's ivars directly. – bearMountain Dec 27 '11 at 06:42
  • 3
    Note: ivars are implicitly defined with `@protected` and should almost never be explicitly `@public`. Defining `@private` explicitly is generally good practice. It is also good practice to prefix ivars with an underscore. A `@property` will in fact implicitly `@synthesize` its associated ivar this way. – walkingbrad Jul 03 '13 at 21:49
5

You can't use KVO and do custom getter and setters with instance variables other than that they are very similar when using ARC.

BJ Homer
  • 48,806
  • 11
  • 116
  • 129
Mattias Wadman
  • 11,172
  • 2
  • 42
  • 57