I am refactoring old code and wonder - with the advent of auto-synthesized properties and class extension, should most instance variables declarations be done in the form of properties as best practice?
2 Answers
Yes, best practice is to use properties, either in the interface file or implementation file class extension based on wether the property is by design public or private to the class.

- 111,848
- 21
- 189
- 228
It would depend on your coding style. Generally, put ivars that you want accessible to other classes as properties in the .h-file.
If you declare properties but leave @synthesize
to the compiler, they will automatically be synthesized so that the property myInstanceVariable
is internally called _myInstanceVariable
.
Accessing _myInstanceVariable
directly means that you will bypass any setters/getters which is sometimes desired internally in classes, especially when the getter creates an object.
However, often when I have internal simple ivars which don't require any setter/getter, I use the ivars directly in the class extension:
// MyClass.m
#import MyClass.h
@interface MyClass() {
BOOL _simpleInternalVariable;
NSUInteger _anotherSimpleInternalVariable;
}
@end
@implementation MyClass
- (void)someMethod
{
_simpleInternalVariable = YES;
_anotherSimpleInternalVariable = 4;
}
@end
This yields exactly the same result as @property BOOL simpleInternalVariable;
except that you are sure that no setter/getter is automatically created by the compiler. I sometimes prefer this way because you can't write self.simpleInternalVariable
. Writing self.ivar means a getter runs somewhere but you don't always know if it's a custom getter or synthesized getter. When writing _ivar, I always know that I'm dealing with the ivar directly.
For objects though, I always use properties both in the .h- and .m-files. I could theoretically do the same thing I did above with objects, but it's just a reflex from the non-ARC days where you always wanted the compiler to generate setters which retained/released objects.

- 5,798
- 4
- 36
- 51