An instance variable is unique to a class. By default, only the class and subclasses can access it. Therefore, as a fundamental principal of object-oriented programming, instance variables (ivars) are private—they are encapsulated by the class.
By contrast, a property is a public value that may or may not correspond to an instance variable. If you want to make an ivar public, you'd probably make a corresponding property. But at the same time, instance variables that you wish to keep private do not have corresponding properties, and so they cannot be accessed from outside of the class. You can also have a calculated property that does not correspond to an ivar.
Without a property, ivars can be kept hidden. In fact, unless an ivar is declared in a public header it is difficult to even determine that such an ivar exists.
A simple analogy would be a shrink-wrapped book. A property might be the title
, author
or hardcover vs. softcover. The "ivars" would be the actual contents of the book. You don't have access to the actual text until you own the book; you don't have access to the ivars unless you own the class.
More interestingly, properties are better integrated into the runtime. Modern 64-bit runtimes will generate an ivar for accessor properties, so you don't even need to create the ivar. Properties are in fact methods:
// This is not syntactically correct but gets the meaning across
(self.variable) == ([self variable];)
(self.variable = 5;) == ([self setVariable:5];)
For every property, there are two methods (unless the property is declared readonly
, in which case there is only one): there is the getter, which returns the same type as the ivar and is of the same name as the ivar, as well as the setter (which is not declared with a readonly
ivar); it returns void and its name is simply set prepended to the variable name.
Because they are methods, you can make dynamic calls on them. Using NSSelectorFromString() and the various performSelector: methods, you can make a very dynamic program with many possibilities.
Finally, properties are used extensively in Core Data and with Key-Value Coding. Core Data is an advanced framework for storing data in a SQLite database while providing a clear Obj-C front-end; KVC is used throughout Core Data and is a dynamic way to access properties. It is used when encoding/decoding objects, such as when reading from XIBs.