O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 the curly-braces part of the class’s interface 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.) So the interface section for the Dog class might look like this:

@interface Dog : NSObject {
    int number;
}
// public method declarations 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 issues of memory management I don’t want to get into 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, meaning that other classes (except for subclasses) can’t see them. So if, somewhere else, I instantiate ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required