How can I make my framework's code automatically run when the app launches?
Objective-C classes derived from NSObject
have the class methods +initialize
and +load
.
The first one is run the first time you send a message to the class, so it is of no use unless you do something in -application:didFinishLaunchingWithOptions:
as you mentioned.
The second one is called exactly once for each class in the app, even if it is not used:
Discussion
The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.
The order of initialization is as follows:
All initializers in any framework you link to.
All +load methods in your image.
All C++ static initializers and C/C++ attribute(constructor) functions in your image.
All initializers in frameworks that link to you.
In addition:
A class’s +load method is called after all of its superclasses’ +load methods.
A category +load method is called after the class’s own +load method.
In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.
Source: Apple's Official Documentation (NSObject Class Reference).
Perhaps you could place your initialization logic there.
If you are using swift, I don't know of any method.