Home iOS & Swift Books UIKit Apprentice

24
Objects vs. Classes Written by Matthijs Hollemans & Fahim Farook

Time for something new. Up until now I’ve been calling almost everything an “object.” That’s not quite correct though. So, it’s time for you to brush up on your programming theory a bit more.

In this chapter, you will learn the following:

  • Classes: The difference between classes and objects.
  • Inheritance: What class inheritance is and how it works.
  • Overriding methods: Overriding methods in sub-classes to provide different functionality.
  • Casts: Casting an object from a subclass to its superclass — how (and why) you do it.

Classes

If you want to use the proper object-oriented programming vernacular, you have to make a distinction between an object and its class.

When you do this,

class ChecklistItem: NSObject {
  . . .
}

You’re really defining a class named ChecklistItem, not an object. An object is what you get when you instantiate a class:

let item = ChecklistItem()

The item variable now contains an object of the class ChecklistItem. You can also say: the item variable contains an instance of the class ChecklistItem. The terms object and instance mean the same thing.

In other words, “instance of class ChecklistItem” is the type of this item variable.

The Swift language and the iOS frameworks already come with a lot of types built-in, but you can also add types of your own by making new classes.

Let’s use an example to illustrate the difference between a class and an instance / object.

You and I are both hungry, so we decide to eat some ice cream — my favorite subject next to programming!. Ice cream is the class of food that we’re going to eat.

The ice cream class looks like this:

class IceCream: NSObject {
  var flavor: String
  var scoops: Int

  func eatIt() {
    // code goes in here
  }
}

You and I go on over to the ice cream stand and ask for two cones:

// one for you
let iceCreamForYou = IceCream()
iceCreamForYou.flavor = "Strawberry"
iceCreamForYou.scoops = 2

// and one for me
let iceCreamForMe = IceCream()
iceCreamForMe.flavor = "Pistachio"
iceCreamForMe.scoops = 3

Yep, I get more scoops, but that’s because I’m hungry from all this explaining. ;-]

Now the app has two instances of IceCream, one for you and one for me. There is just one class that describes what sort of food we’re eating — ice cream — but there are two distinct objects. Your object has strawberry flavor, mine pistachio.

The class is a template for making new instances
The class is a template for making new instances

The IceCream class is like a template that declares: objects of this type have two properties, flavor and scoops, and a method named eatIt().

Any new instance that is made from this template will have those instance variables and methods, but it lives in its own section of computer memory and therefore has its own values.

If you’re more into architecture than food, you can also think of a class as a blueprint for a building. It is the design of the building but not the building itself. One blueprint can make many buildings, and you could paint each one — each instance — a different color if you wanted to.

Inheritance

Sorry, this is not where I tell you that you’ve inherited a fortune. We’re talking about class inheritance here, one of the main principles of object-oriented programming.

class IceCream: NSObject {
class ChecklistViewController: UITableViewController
All framework classes stand on the shoulders of NSObject
Amc hcoqusuzt staqdoj lmorf ed sni jguukyuwg eq QBEysucy

Superclasses and subclasses

When programmers talk about inheritance, they’ll often throw around the terms superclass and subclass.

Superclass and subclass
Takefjmemf ojs ciqbtavl

A small portion of the UIKit inheritance tree
A qhunb solqaib ud dfe OEPik icfinenipli vpae

class IceCream {
  . . .
}

Inheriting properties (and methods)

Inheriting from a class means your new class gets to use the properties and methods from its superclass.

class Snack {
  var flavor: String
  func eatIt() {
    // code goes in here
  }
}
class IceCream: Snack {
  var scoops: Int
}
let iceCreamForMe = IceCream()
iceCreamForMe.flavor = "Chocolate"
iceCreamForMe.scoops = 1
iceCreamForMe.eatIt()

Overriding methods

In the previous example, IceCream could use the eatIt() method implementation from Snack for free. But that’s not the full story :]

class IceCream: Snack {
  var scoops: Int

  override func eatIt() {
    // code goes in here
  }
}
class IceCream: Snack {
  var scoops: Int
  var isMelted: Bool

  override func eatIt() {
    if isMelted {
      throwAway()
    } else {
      super.eatIt()
    }
  }
}
class MyViewController: UIViewController {
  override func viewWillAppear(_ animated: Bool) {
    // do your own stuff before super

    // don't forget to call super!
    super.viewWillAppear(animated)

    // do your own stuff after super
  }
}
override func tableView(
  _ tableView: UITableView, 
  didSelectRowAt indexPath: IndexPath
) {
  . . .
}

Subclass initialization

When making a subclass, the init methods require special care.

class GradientView: UIView {
  override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = UIColor.black
  }
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }
  . . .
}

Private parts

So… does a subclass get to use all the methods from its superclass? Not quite.

Casts

Often, your code will refer to an instance not by its own class but by one of its superclasses. That probably sounds very weird, so let’s look at an example.

The UITabBarController does not see your subclasses
Cxe AUBaqWomKapcnibdey hoij qok fue zuil wisfqugbow

let controller = segue.destination as! ItemDetailViewController
controller.delegate = self
let controller = segue.destination 
let controller = segue.destination as! ItemDetailViewController

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2020 Razeware LLC

You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.