Chapter 19 – Properties
- Accessor Methods almost always use the same pattern. Wouldn’t it be nice if we didn’t have to keep writing essentially the same thing over and over again? There’s gotta be a better way! Yup! There is.
- A Property is a way to tell the compiler to generate the getter and setter methods for an instance variable automatically.
- Here’s the new BNRPerson.h file. We are able to eliminate the instance variables and the declaration of the Accessor methods and replace them with the
- What? That’s it? Yup.
- Switch to the BNRPerson.m file and this is all we need.
- No accessor methods at all? Yes, that’s correct, no accessor methods. They are still there when you run your code, the compiler has created them for us.
Properties are cool.
- Properties can have one or more property attributes.
- They indicate how properties behave.
- They appear in a comma-delimited list in parenthesis after the
BNRPerson, the properties are declared nonatomic.
- Properties are either
nonatomic. The difference depends on multithreading (which we won’t worry about for this course).
- Other property attributes:
readwriteis the default property attribute.
atomicis also a default property attribute, so you will want to set your properties to
- Many Objective-C programmers will use the term ivar to refer to instance variables.
- So, where are the ivars? They are being generated for us. When we declare a property like this:
The Objective-C compiler is inserting an instance variable into your code like this:
- That’s right it adds the underscore to the name of the property to create the name of the instance variable. There are some situations where you will need to access the ivar directly. Even though they don’t show anywhere in our code, if you use
_heightInMetersit will work. Just be careful not to use this if it is not necessary.
- There is a newer alternative for using accessor methods. It is called Dot Notation. It is a subject that frequently causes arguments in the Objective-C community. Some love the new way and others hate it and cling to the old way. Most developers, especially new ones, are using it now. We will dot notation where appropriate for the rest of the semester.
- Dot Notation example. Here’s the program rewritten with dot notation.
- With Dot Notation, these two lines of code do the exact same thing by calling the setter method.
- And these two lines of code both call the getter methods.
- The one main confusing thing about dot notation is this.
int myWeight = mikey.weightInKilos;
- That line of code is actually calling the getter method, it is not accessing a variable. In fact, the variable is named