Categories
Objective-C

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:

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.

By Raz

I'm 25 years old and I do stuff with computers.