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

时间:2016-02-03 03:33:44

标签: ios cocoa-touch ios-frameworks

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?

2 个答案:

答案 0 :(得分:8)

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.

答案 1 :(得分:1)

要迅速,只需添加一个名为load()的类函数

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

相关问题