Why subclass NSObject?

user185590 picture user185590 · Oct 19, 2009 · Viewed 11.3k times · Source

What is the purpose/use of NSObject in Objective-C? I see classes that extend NSObject like this:

@interface Fraction : NSObject 

In C++ or Java, we don't use any variables like NSObject even though we have preprocessor directives and import statements in both Objective-C and Java.

Why do classes explicitly inherit from NSObject in Objective-C? What are the consequences of not declaring inheritance from NSObject?

Answer

Tim picture Tim · Oct 19, 2009

We use NSObject to explicitly state what a given class inherits from. I'm not sure about C++, but in Java there's something similar - the Object class. The only difference is that Java doesn't require that classes explicitly descend from Object - the language assumes anything that doesn't have a specified parent class descends from Object. Objective-C is different because it allows you to define different root classes - you are allowed to make a class that doesn't inherit from NSObject.

An example of such a different root class is NSProxy.

Have a look at the GNUstep NSObject source, it shows how the methods interact with the objective-c runtime through C functions.

+ (id) allocWithZone:(NSZone*)z
{
  return NSAllocateObject(self, 0, z);
}

- (void) dealloc
{
  NSDeallocateObject (self);
}

+ (BOOL) isSubclassOfClass: (Class)aClass
{
  return GSObjCIsKindOf(self, aClass);
}