Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Category on NSObject also works on Class

Tags:

objective-c

So I have a category on NSObject called CustomCategory, as following:

#import <Foundation/Foundation.h>

@interface NSObject (CustomCategory)

-(BOOL)doSomething;

@end

#import "NSObject+CustomCategory.h"

@implementation NSObject (CustomCategory)

-(BOOL)doSomething
{
    NSLog(@"Done");
    return NO;
}

@end

Ideally, this will work on an object like this:

NSObject* object = [NSObject new];
[object doSomething];

However, I found that it also works in this way with no problem:

[NSObject doSomething];

So I am wondering, since it is an instance method I have added through the category, why it also works on a Class?

like image 445
Xiangdong Avatar asked Sep 27 '22 11:09

Xiangdong


1 Answers

Instance methods on NSObject are also class methods on NSObject.

This works because of the way Objective-C does dynamic dispatch. If you send a message to any object the method implementation is looked up in the objects class. If you send a message to a class then you are sending a regular message to the class object. There the implementation is looked up in the so called meta-class. The meta-classes are automatically generated by the compiler. Class methods are just instance methods of the meta-class. This is handled transparently by the compiler.

Inheritance also works on the meta-class level. So the meta-class for a class inherits from the meta-class of its superclass. We have two parallel inheritance hierarchies there. Only root classes like NSObject are handled differently. There the meta-class can't inherit from the meta-class of the superclass as there is no superclass. For root classes the meta-class inherits from the root class itself.

And since class methods of a class are instance methods of its meta-class and NSObjects meta-class inherits from NSObject itself instance methods on NSObject are also class methods on NSObject.

like image 126
Sven Avatar answered Oct 01 '22 00:10

Sven