Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my framework's code automatically run when the app launches?

I'm building a framework that will be included in other apps. I have some code that needs to be run when the app first starts up.

Many frameworks ask developers to include a line at the beginning of [UIApplicationDelegate application:didFinishLaunchingWithOptions:] to initialize their framework. However, I noticed that Reveal's framework does not require this. Just including the framework in the project is enough to integrate with your app, and launch their web server within your app.

How do they do this?

like image 735
Chris Vasselli Avatar asked Feb 03 '16 03:02

Chris Vasselli


2 Answers

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:

  1. All initializers in any framework you link to.

  2. All +load methods in your image.

  3. All C++ static initializers and C/C++ attribute(constructor) functions in your image.

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

like image 142
Nicolas Miari Avatar answered Oct 23 '22 18:10

Nicolas Miari


For swift, just add a class function named load()

Source: https://developer.apple.com/documentation/objectivec/nsobject/1418815-load

like image 2
Paul Nelson Avatar answered Oct 23 '22 18:10

Paul Nelson