iOS Development

Course No. 10-152-139

Chapter 22 — Class Extensions

Another new part of Objective-C that made it into edition 2.

  • During the summer of 2012 an important concept was added to Objective-C and Class Extensions were born.
  • Let’s look at the Kennel project we wrote earlier in the semester. Here’s the Kennel.h file.
  • Anything declared inside a .h file is available to other classes. The is called public access. Some parts of this class declaration make sense to be public. The two methods are called by other code and need to be public. However, the two @properties should not be public.
  • The principal is called data hiding and is an important part of Object-Orientation.

Data in classes should be private and only accessed through public methods.

Data Hiding in Objective-C

  • Some languages use a keyword like private to mark variables and hide them from outside the class. Objective-C does not have this.
  • Objective-C uses the .h and .m files for public and private resources.
    • Everything declared in a .h file is public.
    • Everything declared in a .m file is private.
  • In order to make the two Kennel properties private we have to move them to the .m file. In order to do this we need to use a new feature of the language: Class Extensions.

Class Extension

  • A class extension is declared at the top of a .m file for a class. Here’s the new Kennel.h file.
  • Here’s the new Kennel.m file with something new in it.
  • The Class Extension is this part.
  • We are extending the class definition inside the Kennel.m file with this code.
  • We start defining the class with its public properties and methods in the Kennel.h file.
  • We then switch to the Kennel.m file and continue defining the class in the class extension. Everything that is in the Kennel.m file is private and can’t be accessed by code in other classes.
  • Class Extensions are defined like this.
  • Inside the class extension you declare properties and methods just like in the .h file. Only these are private.

Headers and inheritance

  • Subclasses do not have access to their super class’s class extension.
  • Subclasses only have access to what’s declared in the superclass’s header file that it imports.