DEV Community

Cover image for Swift native base class NSObject
Swift Anytime
Swift Anytime

Posted on • Edited on • Originally published at swiftanytime.com

Swift native base class NSObject

Description

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. It's the one class that has no superclass.

Core Responsibility:

The NSObject class provides inheriting classes with a framework for creating, initializing, deallocating, copying, comparing, archiving, and unarchiving objects, run-time environment, querying objects, and message forwarding.

The NSObject is an abstract class. You use instances of classes that inherit from NSObject but never of NSObject itself.

Declaration

class NSObject
Enter fullscreen mode Exit fullscreen mode

Initializing an Object to Its Class

Every object is created in the run-time system through its isa instance variable, inherited from the NSObject class. isa identifies the object's class; it points to a structure that's compiled from the class definition. Through isa, an object can find whatever information it needs at run time--such as its place in the inheritance hierarchy, the size, and structure of its instance variables, and the location of the method implementations it can perform in response to messages.

Because all objects directly or indirectly inherit from the NSObject class, they all have this variable. The defining characteristic of an "object" is that its first instance variable is an isa pointer to a class structure.

What if you make a subclass inherited by NSObject?

  • Those classes are Objective-C classes themselves.
  • Use objc_msgSend() for calling all the methods.
  • Provides Objective-C runtime metadata.

What if you do not make a subclass inherited by NSObject?

  • Those classes are Objective-C classes but use compatible methods of NSObject class.
  • Do not use objc_msgSend() for calling their methods.
  • Do not provide Objective-C runtime metadata.

Important: Making a subclass from NSObject gets you Objective-C runtime feature along with Objective-C performance. But you can include or omit NSObject as a superclass.

What next?

Now, you know what is NSObject class is and why it is essential in the Cocoa Touch framework. In the upcoming articles, you will more about UIKit components. Till then,

Eat. Sleep. SwiftAnytime. Repeat.

Top comments (0)