iOS Development

Course No. 10-152-139

Chapter 19 – Properties

Declaring 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 @property statements.
    • 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.

Property attributes

  • Properties can have one or more property attributes.
    • They indicate how properties behave.
    • They appear in a comma-delimited list in parenthesis after the @property annotation.
  • In BNRPerson, the properties are declared nonatomic.
  • Properties are either atomic or nonatomic. The difference depends on multithreading (which we won’t worry about for this course).
  • Other property attributes:
    • readonly
    • readwrite
    • readwrite is the default property attribute.
    • Unfortunately, atomic is also a default property attribute, so you will want to set your properties to nonatomic.

ivars

  • 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 _heightInMeters it will work. Just be careful not to use this if it is not necessary.

Dot Notation

  • 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 _weightInKilos.