Member-only story
Why do we ever need to inherit from NSObject?
Not just for Objective-C Programmers
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:
- Be able to produce a “Hello, World!” iOS application (guide HERE)
- You will be expected to be aware how to make a Single View Application in Swift, or be able to code in Swift Playgrounds
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