天天看点

bee框架学习笔记

问题:为什么AppService类中的+(void)initialize{}函数会先于AppDelegate类的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 执行??

解答:程序一运行的时候会先加载bee框架,会执行到bee框架里面的Bee_Runtime.mm这一个文件里的如下一个函数:

+ (NSArray *)allClasses
{
static NSMutableArray * __allClasses = nil;
if ( nil == __allClasses )
{
__allClasses = [[NSMutableArray alloc] init];
}
if ( 0 == __allClasses.count )
{
unsigned int	classesCount = 0;
Class *	 classes = objc_copyClassList( &classesCount );
for ( unsigned int i = 0; i < classesCount; ++i )
{
Class classType = classes[i];

            //other codes
}
free( classes );
}
return __allClasses;
}
           

其中 objc_copyClassList( &classesCount ) 这个函数,会创建并返回一个指向所有已注册类定义的指针列表。

当它循环遍历指针列表的时候,遍历到一个指向AppService的类,然后就会执行Appservice类中的+(void)initialize{}函数(why?see introduce of initialise below),执行完Bee框架里的东西之后程序才会去执行- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions ,导致先执行AppService类的+(void)initialize{}函数,然后才执行AppDelegate类的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions执行

附注:

关于 objc_copyClassList 和 initializer 函数的介绍,摘录苹果官网的介绍如下:

Class *objc_copyClassList(unsigned int *outCount)
Description Creates and returns a list of pointers to all registered class definitions.
See Also: objc_getClassList
Parameters
outCount An integer pointer used to store the number of classes returned by this function in the list. It can be nil.
Returns A nil terminated array of classes. It must be freed with free().
Declaration + (void)initialize
Description Initializes the receiver before it’s used (before it receives its first message).
The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
initialize it is invoked only once per class. If you want to perform independent initialization for the class and for categories of the class, you should implement load methods.