Why subclass NSObject?

前端 未结 5 1097
梦谈多话
梦谈多话 2020-12-10 01:46

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

@interface Fraction : NSObject 

In C++ or

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 02:03

    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);
    }
    

提交回复
热议问题