Using ivars to define property values inside a class

47 Views Asked by At

Is accessing the private ivar linked to a property inside of a class method more efficient than using its synthesized getter/setter methods, or is the efficiency just the same? ...As in:


@implementation MyApp

@synthesize name;

- (void)loadView 
{
    _name = @"Savagewood"; // VS.
    self.name = @"Savagewood";
}

@end

I'm guessing the latter takes more time to execute but I want to know what they suggest App developers to use for the sake of consistency and good programming technique and whether both assignments are basically of the same time complexity.

2

There are 2 best solutions below

2
jlehr On BEST ANSWER

In general, it's best to use property accessors wherever possible, and limit the direct use of instance variables to accessor methods, init methods, and dealloc (if you're not using ARC). Conversely, avoid calling accessors in init and dealloc, and avoid using the accessors of the property you're implementing from within it's own accessor methods.

8
Enzo On

The latter would actually call the setter method on the property name. If you override the setter into something like

- (void)setName:(NSString*)name {
  NSLog(@"New name: %@", name);
  _name = name;
}

You'll see that setting ivar directly does not log anything, but the latter would trigger a log.

In terms of cost: I would say setting the ivar is cheaper, but the cost you save is almost negligible. My approach is use property only when necessary, like when you need KVO on a property of an object. Otherwise I always use an ivar.