iOS 中 attribute((constructor)) 修饰的函数

2024-06-18 20:36

本文主要是介绍iOS 中 attribute((constructor)) 修饰的函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

开发环境声明:此文描述的 attribute((constructor)) 特指使用 Objective-C 开发 iOS、MacOS,Swift 语言不支持这种属性修饰符。

初识 attribute((constructor))

在 Objective-C 开发中,attribute((constructor)) 是一个 GCC 和 Clang 编译器特性,允许开发者在程序启动时自动执行一些函数。使用这个属性修饰的函数会在 main 函数之前执行,通常用于初始化一些全局状态或者执行一些在程序开始时就需要完成的操作。

使用 attribute((constructor))

这种属性的使用方法很简单,只需要在函数定义前加上 __attribute__((constructor)) 修饰符即可。

#import <Foundation/Foundation.h>__attribute__((constructor))
void myCustomInitializer(void) {NSLog(@"This function is called before main");
}int main(int argc, const char * argv[]) {@autoreleasepool {NSLog(@"Hello, World!");}return 0;
}

在上面的代码中,myCustomInitializer 函数会在 main 函数之前执行。当你运行这个程序时,你会看到控制台输出:

This function is called before main
Hello, World!

应用场景

  1. 全局状态初始化:可以用于初始化一些全局变量或状态,这些变量在程序开始时就需要使用。
  2. 日志初始化:如果有全局的日志系统,可以在程序启动时进行初始化。
  3. 注册插件或模块:在应用启动时自动注册一些插件或模块,使其在整个应用生命周期中可用。

注意事项

  1. 执行顺序:如果有多个使用 attribute((constructor)) 修饰的函数,执行顺序是不确定的,因此不要依赖于特定的执行顺序。
  2. 执行时间:这些函数会在 main 函数之前执行,因此会增加应用的启动时间,要谨慎使用,尽量避免进行耗时操作。
  3. Objective-C 的使用:虽然可以在 Objective-C 中使用,但要注意和 Objective-C runtime 的初始化顺序相互配合,避免在 Objective-C runtime 尚未完全初始化时进行依赖 Objective-C 特性的操作。

更复杂的例子

下面是一个更复杂的例子,展示了如何使用 attribute((constructor)) 初始化一个全局对象:

#import <Foundation/Foundation.h>@interface MyGlobalManager : NSObject
+ (void)initializeManager;
@end@implementation MyGlobalManager+ (void)initializeManager {NSLog(@"MyGlobalManager is initialized");// 全局初始化代码
}@end__attribute__((constructor))
void initializeGlobalManager(void) {[MyGlobalManager initializeManager];
}int main(int argc, const char * argv[]) {@autoreleasepool {NSLog(@"Application is starting");// 应用的其他代码}return 0;
}

运行这个程序,你会看到:

MyGlobalManager is initialized
Application is starting


What about attribute((constructor)) in Swift ?

在 Swift 中,无法直接使用 __attribute__((constructor)) 这种 GCC/Clang 特性,因为 Swift 语言不支持这种属性修饰符 (已经在开头声明)。不过,我们可以通过其他方法实现类似的效果,例如使用 @UIApplicationMain、全局变量的初始化方法、或使用 Objective-C 的方法结合 Swift 来达到在程序启动时执行某些代码的目的。

使用 Swift 实现类似效果

1. 全局变量的初始化

Swift 中全局变量在应用启动时会初始化,可以利用这一特性来执行一些初始化代码。

import Foundationlet initialize: Void = {print("This code runs before main")
}()@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {print("Application did finish launching")return true}
}

在这个例子中,全局变量 initialize 在应用启动时会被初始化,因此其闭包中的代码会在 main 函数之前执行。

2. 使用 Objective-C 桥接

如果需要使用 __attribute__((constructor)) 特性,可以在 Objective-C 文件中定义,然后在 Swift 中调用。

Objective-C 部分

创建一个 Objective-C 文件,例如 Initializer.m

// Initializer.m
#import <Foundation/Foundation.h>__attribute__((constructor))
static void myConstructor() {NSLog(@"Objective-C constructor is called before main");
}

创建一个桥接头文件,例如 YourProject-Bridging-Header.h,并在其中导入 Initializer.h

// YourProject-Bridging-Header.h
#import "Initializer.h"

Swift 部分

确保在 Xcode 项目的设置中配置了桥接头文件,然后正常使用 Swift 编写应用:

import UIKit@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {print("Application did finish launching")return true}
}

运行这个项目时,控制台会输出:

Objective-C constructor is called before main
Application did finish launching

3. 使用 UIApplicationMain

在 Swift 中,@UIApplicationMain 会自动生成一个 main 函数并处理应用的启动过程,实际上你很少需要显式编写初始化代码。通过在 AppDelegate 中的 application(_:didFinishLaunchingWithOptions:) 方法中进行初始化,也能实现类似效果:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {// 初始化代码print("Application did finish launching")return true}
}

通过 attribute((constructor)) 实现组件化

通过 __attribute__((constructor)) 实现组件化的主要思路是利用这一特性来自动注册或初始化组件,使得每个组件在应用启动时都能自动执行其初始化代码。这在模块化或插件化系统中非常有用,因为它可以自动地将组件注册到系统中,而不需要在应用启动时显式地调用每个组件的初始化代码。

下面详细说明如何通过 __attribute__((constructor)) 实现组件化,并提供一个具体的例子。

组件化的基本思路

  1. 定义一个组件协议:每个组件都需要实现这个协议。
  2. 组件注册器:一个全局的组件注册器,用来管理所有注册的组件。
  3. 使用 __attribute__((constructor)):每个组件通过 __attribute__((constructor)) 注册到全局注册器中。

具体步骤

1. 定义组件协议

首先,定义一个组件协议(例如 Component),所有组件都需要实现这个协议:

// Component.h
#import <Foundation/Foundation.h>@protocol Component <NSObject>
@required
- (void)initializeComponent;
@end
2. 组件注册器

创建一个全局的组件注册器,用来管理和调用所有注册的组件:

// ComponentRegistry.h
#import <Foundation/Foundation.h>@interface ComponentRegistry : NSObject
+ (instancetype)sharedInstance;
- (void)registerComponent:(id<Component>)component;
- (void)initializeAllComponents;
@end// ComponentRegistry.m
#import "ComponentRegistry.h"@interface ComponentRegistry ()
@property (nonatomic, strong) NSMutableArray<id<Component>> *components;
@end@implementation ComponentRegistry+ (instancetype)sharedInstance {static ComponentRegistry *sharedInstance = nil;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{sharedInstance = [[self alloc] init];});return sharedInstance;
}- (instancetype)init {if (self = [super init]) {_components = [NSMutableArray array];}return self;
}- (void)registerComponent:(id<Component>)component {[self.components addObject:component];
}- (void)initializeAllComponents {for (id<Component> component in self.components) {[component initializeComponent];}
}@end
3. 定义组件并使用 __attribute__((constructor)) 进行注册

每个组件通过 __attribute__((constructor)) 将自己注册到组件注册器中:

// MyComponent.h
#import <Foundation/Foundation.h>
#import "Component.h"@interface MyComponent : NSObject <Component>
@end// MyComponent.m
#import "MyComponent.h"
#import "ComponentRegistry.h"@implementation MyComponent- (void)initializeComponent {NSLog(@"MyComponent is initialized");
}__attribute__((constructor))
static void registerMyComponent(void) {MyComponent *component = [[MyComponent alloc] init];[[ComponentRegistry sharedInstance] registerComponent:component];
}@end
4. 在应用启动时初始化所有组件

AppDelegateapplication:didFinishLaunchingWithOptions: 方法中,调用组件注册器的初始化方法:

// AppDelegate.m
#import "AppDelegate.h"
#import "ComponentRegistry.h"@interface AppDelegate ()
@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// Initialize all registered components[[ComponentRegistry sharedInstance] initializeAllComponents];return YES;
}@end

完整的示例

  1. Component.h
#import <Foundation/Foundation.h>@protocol Component <NSObject>
@required
- (void)initializeComponent;
@end
  1. ComponentRegistry.h
#import <Foundation/Foundation.h>
#import "Component.h"@interface ComponentRegistry : NSObject
+ (instancetype)sharedInstance;
- (void)registerComponent:(id<Component>)component;
- (void)initializeAllComponents;
@end
  1. ComponentRegistry.m
#import "ComponentRegistry.h"@interface ComponentRegistry ()
@property (nonatomic, strong) NSMutableArray<id<Component>> *components;
@end@implementation ComponentRegistry+ (instancetype)sharedInstance {static ComponentRegistry *sharedInstance = nil;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{sharedInstance = [[self alloc] init];});return sharedInstance;
}- (instancetype)init {if (self = [super init]) {_components = [NSMutableArray array];}return self;
}- (void)registerComponent:(id<Component>)component {[self.components addObject:component];
}- (void)initializeAllComponents {for (id<Component> component in self.components) {[component initializeComponent];}
}@end
  1. MyComponent.h
#import <Foundation/Foundation.h>
#import "Component.h"@interface MyComponent : NSObject <Component>
@end
  1. MyComponent.m
#import "MyComponent.h"
#import "ComponentRegistry.h"@implementation MyComponent- (void)initializeComponent {NSLog(@"MyComponent is initialized");
}__attribute__((constructor))
static void registerMyComponent(void) {MyComponent *component = [[MyComponent alloc] init];[[ComponentRegistry sharedInstance] registerComponent:component];
}@end
  1. AppDelegate.m
#import "AppDelegate.h"
#import "ComponentRegistry.h"@interface AppDelegate ()
@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// Initialize all registered components[[ComponentRegistry sharedInstance] initializeAllComponents];return YES;
}@end

要点总结

__attribute__((constructor)) 是一个非常有用的特性,允许开发者在程序启动时自动执行一些初始化操作。不过在使用时要注意性能影响和执行顺序,避免对应用启动时间产生负面影响。它适用于需要在应用启动时进行一些全局初始化工作的场景,但要避免在这些函数中进行耗时的操作。

虽然 Swift 本身不支持 __attribute__((constructor)),但我们可以通过全局变量初始化、使用 Objective-C 桥接以及在 AppDelegate 中进行初始化来实现类似的效果。这些方法在实际开发中都非常实用,并且可以满足绝大多数初始化需求。

通过 __attribute__((constructor)) 特性,可以在应用启动时自动注册和初始化各个组件,从而实现模块化和插件化的效果。这种方法简化了组件的初始化流程,使代码更具模块化和可扩展性。不过,在使用这种技术时,要注意性能影响和组件的初始化顺序问题,以确保应用能稳定、高效地启动。

这篇关于iOS 中 attribute((constructor)) 修饰的函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1073018

相关文章

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

MySQL高级查询之JOIN、子查询、窗口函数实际案例

《MySQL高级查询之JOIN、子查询、窗口函数实际案例》:本文主要介绍MySQL高级查询之JOIN、子查询、窗口函数实际案例的相关资料,JOIN用于多表关联查询,子查询用于数据筛选和过滤,窗口函... 目录前言1. JOIN(连接查询)1.1 内连接(INNER JOIN)1.2 左连接(LEFT JOI

MySQL中FIND_IN_SET函数与INSTR函数用法解析

《MySQL中FIND_IN_SET函数与INSTR函数用法解析》:本文主要介绍MySQL中FIND_IN_SET函数与INSTR函数用法解析,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一... 目录一、功能定义与语法1、FIND_IN_SET函数2、INSTR函数二、本质区别对比三、实际场景案例分

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

C语言函数递归实际应用举例详解

《C语言函数递归实际应用举例详解》程序调用自身的编程技巧称为递归,递归做为一种算法在程序设计语言中广泛应用,:本文主要介绍C语言函数递归实际应用举例的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录前言一、递归的概念与思想二、递归的限制条件 三、递归的实际应用举例(一)求 n 的阶乘(二)顺序打印

C/C++错误信息处理的常见方法及函数

《C/C++错误信息处理的常见方法及函数》C/C++是两种广泛使用的编程语言,特别是在系统编程、嵌入式开发以及高性能计算领域,:本文主要介绍C/C++错误信息处理的常见方法及函数,文中通过代码介绍... 目录前言1. errno 和 perror()示例:2. strerror()示例:3. perror(

Kotlin 作用域函数apply、let、run、with、also使用指南

《Kotlin作用域函数apply、let、run、with、also使用指南》在Kotlin开发中,作用域函数(ScopeFunctions)是一组能让代码更简洁、更函数式的高阶函数,本文将... 目录一、引言:为什么需要作用域函数?二、作用域函China编程数详解1. apply:对象配置的 “流式构建器”最

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程