I encountered a weird behavior of Cocoa Touch / iOS involving static method. If you implement a static method ‘load’ in any class, Cocoa Touch / iOS will automatically call that method when the application starts executing. Even if you do not refer to that class from the main execution thread, it’ll still be called first, no matter what.
I’ve managed to replicate the behavior when compiled on SDK 4.2 on Xcode 3.2.5 and SDK 4.3 on Xcode 4.0.1, and when running from both iPhone simulator and iPhone device.
Here’s how to replicate:
Create a new class and name it however you want. In the interface declare a static method ‘load’ (any return type):
+ (void)load;
Then implement it:
+ (void)load {
NSLog(@"What the?");
}
Compile (make sure the new class is compiled along) and run the app (on simulator or device). While the app is starting, switch to and monitor GDB view. You’ll see “What the?” echoed there even though by logic no other code refers to the class or the method.
And on top of that, if you use any autorelease code in the method, you’ll get an error that shows that the method is called before even the int main() method (the super gateway of all C applications existing out there).
The following code:
+ (void)load {
NSLog(@"Hello %@", [NSString stringWithString:@"World"]);
}
Will give you something that looks like:
2011-04-21 00:41:53.828 AppName[548:707] *** __NSAutoreleaseNoPool(): Object 0x8fe8c of class NSCFString autoreleased with no pool in place - just leaking
2011-04-21 00:41:53.838 AppName[548:707] Hello World
So the questions are, does anyone know why Cocoa Touch / iOS calls this method? What’s so special about method name ‘load’? And last but not least, is this a feature or a bug?
p/s: I discovered this behavior when it just so happened that the static method ‘load’ that I implemented instantiates many autoreleased objects and I was perplexed by the multiple __NSAutoreleaseNoPool() warning messages in GDB.
NSObject has a +(void)load method. Here is what the documentation says :
So this is working as intended, and is not a bug. This method gets called by every class when it is added to the runtime, which is before any code begins to be executed.
Source: NSObject documentation