Member-only story

Why do we ever need to inherit from NSObject?

Not just for Objective-C Programmers

--

Photo by Namroud Gorguis on Unsplash

You might want to inherit from NSObject. What does that mean, and why would you ever want to?

This article and accompanying video seeks to explain how.

Prerequisites:

Terminology

NSObject: The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects

Objective-C: An Object Oriented language

Subclassing: This is the act of basing a new class on an existing class

NSObject

NSObject is the root class of most Objective-C hierarchies, from which subclasses inherit an interface to the runtime system and have the ability to behave as Objective-C objects.

Performance

Swift is known to be faster than Objective-C, and inheriting the interface gives you a performance disbenefit against running pure Swift code.

Benefits of subclassing NSObject

These classes are actually Objective-C classes, meaning that classes inheriting from NSObject are in some sense “Objective-C compatible”.

Subclassing NSObject in Swift gets you Objective-C runtime flexibility but also Objective-C performance. Avoiding NSObject can improve performance if you don’t need Objective-C’s flexibility.

Swift classes that are subclasses of NSObject:

  • are Objective-C classes themselves
  • use objc_msgSend() for calls to (most of) their methods

--

--

Responses (1)

Write a response