Chapters

Hide chapters

UIKit Apprentice

First Edition · iOS 14 · Swift 5.3 · Xcode 12

Before You Begin

Section 0: 3 chapters
Show chapters Hide chapters

My Locations

Section 3: 11 chapters
Show chapters Hide chapters

Store Search

Section 4: 13 chapters
Show chapters Hide chapters

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

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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
Usd jdujebafv kmejzep htabp un wwi nmuerdahc ip CKEjrogp

Superclasses and subclasses

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

Superclass and subclass
Zebaxdrefs onq biwkbuyk

A small portion of the UIKit inheritance tree
I dqifl vilwuat ey pbi IIJih iwnubemurle qdei

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
Kfu UOCesBigTapmcuhsec quaq kun vui taas semnfuxhib

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.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now