Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a root object in Objective-C without NSObject?

Tags:

objective-c

The documentation says:

While not strictly a part of the language, the isa pointer is required for an object to work with the Objective-C runtime system. An object needs to be “equivalent” to a struct objc_object (defined in objc/objc.h) in whatever fields the structure defines. However, you rarely, if ever, need to create your own root object, and objects that inherit from NSObject or NSProxy automatically have the isa variable.

While that sounds nice, I wonder how an root object would be created in Objective-C anyways?

This is for learning purposes. I just want to know this. I'd really like to see it.

like image 669
Another Registered User Avatar asked Dec 02 '09 20:12

Another Registered User


People also ask

How do I create an NSObject in Objective-C?

Creating a Custom Class Go ahead an choose “Objective-C class” and hit Next. For the class name, enter “Person.” Make it a subclass of NSObject. NSObject is the base class for all objects in Apple's developer environment. It provides basic properties and functions for memory management and allocation.

What is an NSO object?

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.

What is the use of NSObject class in Swift?

This is because Objective-C is all about objects sending messages to other object. NSObject exists to mark a class in Swift that you will provide that basic functionality — basically Objective-C needs you to build up from a base class with your functionality on top (That is, NSObject is a Universal Base Class).

What is NSObject Swiftui?

NSObject is what's called a universal base class for all Cocoa Touch classes. That means all UIKit classes ultimately come from NSObject , including all of UIKit.


1 Answers

It's actually a "trap" some people migrating from C# or Java style languages fall into. You simply don't specify a superclass when declaring your class i.e.

@interface MyNewRoot {
Class isa;
}
@end

vs

@interface MyObject : NSObject {
}
@end

In Java or C# these would be equivalent (in the first case the compiler would assume System.Object or java.lang.Object was the superclass), but in Objective-C no such default will be assumed, and hence a new root is created.

However you're now responsible for a number of features for your class that you typically take for granted (even simple things like memory management for allocating or destorying new instances etc). This is what the comment you quoted hints at when it talks about struct objc_object and the isa instance variable etc.

like image 150
Christopher Fairbairn Avatar answered Sep 18 '22 11:09

Christopher Fairbairn