Ghost Classes

By exploiting a property of the Objective-C runtime, it’s possible to have a class living and breathing in memory without it ever have been imported, allocated, nor initialized anywhere else in the code base. The property in question is the +load message that is sent to every NSObject shortly after a class is loaded into memory. Consider the following implementation of a hypothetical class called MyClass:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@implementationMyClass

+(void)load{

[[selfsharedInstance] run];

}

+(instancetype)sharedInstance{

staticMyClass*sharedClass;

staticdispatch_once_t onceToken;

dispatch_once(&onceToken,^{

sharedClass=[selfnew];

});

returnsharedClass;

}

-(void)run{

// Do stuff

}

@end

Upon MyClass getting loaded into memory, +load is called by the runtime, which allocates, instantiates, and retains an instance of MyClass and then calls -run to do some arbitrary work. MyClass is not #imported from anywhere else, and it is also not retained by anyone else either. It’s there but you can’t see it.

In practice this is probably a bad idea because of the sneaky nature of things. So have a good reason before deciding to use something like this.