Instance Variables and Accessors

In Chapter 3, I explained that one of the main reasons there are instances and not just classes is that instances can have instance variables. Instance variables, you remember, are declared when you define the class, and in Chapter 4 I said that these declarations go into curly braces at the start of the class’s interface section or, in modern Objective-C, its implementation section. But the value of an instance variable differs for each instance.

Note

The term “instance variable” arises so often that it is often abbreviated to ivar. I’ll use both terms indiscriminately from now on.

Let’s write a class that uses an instance variable. Suppose we have a Dog class and we want every Dog instance to have a number, which should be an int. (For example, this number might correspond to the dog’s license number, or something like that.) In modern Objective-C, we would probably declare number in the implementation section for the Dog class, like this:

@implementation Dog {
    int number;
}
// method implementations go here
@end

(You might ask why, for this example, I don’t use instead the concept of giving the dog a name. The reason is that a name would be an NSString instance, which is an object; instance variables that are pointers to objects raise some additional issues I don’t want to discuss just now. But instance variables that are simple C data types raise no such issues. We’ll return to this matter in Chapter 12.)

By default, instance variables are protected ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.