tricks – Raz https://blog.razb.me Computer stuff Sun, 13 Jan 2019 01:25:31 +0000 en-US hourly 1 https://wordpress.org/?v=5.0.3 https://i2.wp.com/blog.razb.me/wp-content/uploads/2018/04/cropped-Untitled.png?fit=32%2C32&ssl=1 tricks – Raz https://blog.razb.me 32 32 108306310 Ghost Classes https://blog.razb.me/hello-world/ https://blog.razb.me/hello-world/#respond Sat, 12 Mar 2016 06:01:33 +0000 http://razb.me/?p=1 Read more…]]> 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:

@implementation MyClass

+ (void)load {
    [[self sharedInstance] run];
}

+ (instancetype)sharedInstance {
    static MyClass *sharedClass;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClass = [self new];
    });
    return sharedClass;
}

- (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.

]]>
https://blog.razb.me/hello-world/feed/ 0 1