当应用程序启动时,如何使我的框架代码自动 运行?
How can I make my framework's code automatically run when the app launches?
我正在构建一个将包含在其他应用程序中的框架。当应用程序首次启动时,我有一些代码需要 运行。
许多框架要求开发人员在 [UIApplicationDelegate application:didFinishLaunchingWithOptions:]
的开头包含一行以初始化他们的框架。但是,我注意到 Reveal 的框架不需要这个。只需在项目中包含框架就足以与您的应用程序集成,并在您的应用程序中启动他们的网络服务器。
他们是怎么做到的?
Objective-C class 派生自 NSObject
的 es 具有 class 方法 +initialize
和 +load
.
第一个是 运行 你第一次向 class 发送消息时,所以它没有用,除非你像你提到的那样在 -application:didFinishLaunchingWithOptions:
中做一些事情。
第二个在应用程序中为每个 class 调用一次,即使未使用也是如此:
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.
来源: Apple's Official Documentation (NSObject Class Reference).
也许您可以将初始化逻辑放在那里。
如果你用的是swift,我不知道有什么方法。
对于swift,只需添加一个名为load()
的class函数
来源:https://developer.apple.com/documentation/objectivec/nsobject/1418815-load
我正在构建一个将包含在其他应用程序中的框架。当应用程序首次启动时,我有一些代码需要 运行。
许多框架要求开发人员在 [UIApplicationDelegate application:didFinishLaunchingWithOptions:]
的开头包含一行以初始化他们的框架。但是,我注意到 Reveal 的框架不需要这个。只需在项目中包含框架就足以与您的应用程序集成,并在您的应用程序中启动他们的网络服务器。
他们是怎么做到的?
Objective-C class 派生自 NSObject
的 es 具有 class 方法 +initialize
和 +load
.
第一个是 运行 你第一次向 class 发送消息时,所以它没有用,除非你像你提到的那样在 -application:didFinishLaunchingWithOptions:
中做一些事情。
第二个在应用程序中为每个 class 调用一次,即使未使用也是如此:
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.
来源: Apple's Official Documentation (NSObject Class Reference).
也许您可以将初始化逻辑放在那里。
如果你用的是swift,我不知道有什么方法。
对于swift,只需添加一个名为load()
的class函数来源:https://developer.apple.com/documentation/objectivec/nsobject/1418815-load