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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/29445.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网络变压器内部加电容起什么作用

网络变压器内部加入电容的作用是多方面的&#xff0c;主要涉及信号耦合、电磁兼容&#xff08;EMC&#xff09;和信号完整性&#xff08;SI&#xff09;等方面。下面详细解释&#xff1a; 1. **信号耦合**&#xff1a; 网络变压器的主要功能是增加信号的传输距离和提升信号…

【前端】 nvm安装管理多版本node、 npm install失败解决方式

【问题】If you believe this might be a permissions issue, please double-check the npm ERR! permissio或者Error: EPERM: operation not permitted, VScode中npm install或cnpm install报错 简单总结&#xff0c;我们运行npm install 无法安装吧包&#xff0c;提示权限问题…

友思特应用 | 模型链接一应俱全:IC多类别视觉检测一站式解决方案

导读 高精度IC制造工艺需要对产品进行全方位检测以保证工艺质量过关。友思特 Neuro-T 通过调用平台的流程图功能&#xff0c;搭建多类深度学习模型&#xff0c;形成了一站式的视觉检测解决方案。本文将为您详述方案搭建过程与实际应用效果。 在当今集成电路&#xff08;IC&…

谷歌浏览器切换tab栏时页面释放内存导致echarts不显示问题

在初始化echarts时添加下述监听 // 添加事件监听器document.addEventListener("visibilitychange", this.handleVisibilityChange);handleVisibilityChange() {if (document.visibilityState visible) {// 页面处于活动状态&#xff0c;手动触发图表的更新或重新绘…

SuiNS更新命名标准,增强用户体验

SuiNS将其面向用户的命名标准从 xxx.sui 更新为 xxx&#xff0c;让用户能够以一种适用于Web2和Web3世界的方式来代表自己。通过此更新&#xff0c;用户可以在其选择的名称前使用 &#xff0c;而不是在名称后添加 .sui。 Sui命名服务于去年推出&#xff0c;旨在使Sui上的地址更…

TypeScript写好了,怎么运行啊!!!

环境搭建 Vs code Ctrlshiftp打开首选项—》打开工作区设置—》搜索Typescript 推荐开启的配置项主要是这几个&#xff1a; Function Like Return Types&#xff0c;显示推导得到的函数返回值类型&#xff1b;Parameter Names&#xff0c;显示函数入参的名称&#xff1b;Par…

Vxe UI vxe-modal 实现窗口的最大化与最小化,实现弹出多窗口

Vxe UI vue vxe-modal 实现窗口的最大化与最小化&#xff0c;实现弹出多窗口 通过js方式调用 js方式脱离模板&#xff0c;每次创建是多个实例。 mask&#xff1a;关闭遮罩层&#xff0c;如果不关闭则会显示遮罩层&#xff0c;就不能实现同时操作多窗口 lockView&#xff1a;…

win11右键小工具

开头要说的 在日常使用场景中&#xff0c;大家如果用的是新的笔记本电脑&#xff0c;应该都是安装的win11系统&#xff0c; 当然win11系统是最被诟病的&#xff0c; 因为有很多人觉得很难操作&#xff0c; 就比如一个小小的解压操作&#xff0c; 在win7和win10上&#xff…

Kubernetes CSR 颁发的 MinIO Operator 证书

在当前的 Kubernetes 环境中&#xff0c;创建、管理和自动化 TLS 证书的标准方法是使用 kind: CertificateSigningRequest &#xff08;CSR&#xff09;资源。此原生 Kubernetes 资源提供了一种强大而高效的方式来处理集群中证书的整个生命周期。 通过利用 CSR 资源&#xff0…

小山菌_代码随想录算法训练营第二十六天| 39. 组合总和 、40.组合总和II 、 131.分割回文串

39. 组合总和 文档讲解&#xff1a;代码随想录.组合总和 视频讲解&#xff1a;带你学透回溯算法-组合总和&#xff08;对应「leetcode」力扣题目&#xff1a;39.组合总和&#xff09;| 回溯法精讲&#xff01; 状态&#xff1a;已完成 代码实现 class Solution {private:vecto…

Thinkphp校园新闻发布系统源码 毕业设计项目实例

Thinkphp校园新闻发布系统源码 毕业设计项目实例 校园新闻发布系统模块&#xff1a; 用户模块&#xff1a;注册&#xff0c;登陆&#xff0c;查看个人信息&#xff0c;修改个人信息&#xff0c;站内搜索&#xff0c;新闻浏览等功能&#xff0c; 后台管理员模块&#xff1a;会员…

MySQL日志——redolog

redo log&#xff08;重做日志&#xff09; 为什么需要redo log&#xff1f; 在mysql提交一个事务后&#xff0c;这个事务所作的数据修改并不会直接保存到磁盘文件中&#xff0c;而是先保存在buffer pool缓冲区中&#xff0c;在需要读取数据时&#xff0c;先从缓冲区中找&…

破局消费供应链,企业费用管理如何应对变与不变?

供应链管理在过去一直被局限在生产与产品供应领域&#xff0c;更多被理解为生产及流通过程中&#xff0c;涉及将产品或服务提供给最终用户活动的上游与下游企业所形成的网链结构&#xff0c;即将产品从商家送到消费者手中整个链条。因为直接对企业利润产生重大影响&#xff0c;…

鸿蒙 Text文本过长超出Row的范围问题

代码如下: 可以发现随着文本内容的增加, 第二个组件test2明显被挤出了屏幕外, 感觉像是Row自己对内容的约束没做好一样, 目前没看到官方的推荐解决方法, 机缘巧合下找到了个这种的办法, 给内容会增加的组件设置layoutWeight(), 借助layoutWeight的特性来解决该问题, 改动后代码…

MaxKB-无需代码,30分钟创建基于大语言模型的本地知识库问答系统

简介 MaxKB 是一个基于大语言模型 (LLM) 的智能知识库问答系统。它能够帮助企业高效地管理知识&#xff0c;并提供智能问答功能。想象一下&#xff0c;你有一个虚拟助手&#xff0c;可以回答各种关于公司内部知识的问题&#xff0c;无论是政策、流程&#xff0c;还是技术文档&a…

简析:分账系统

分账系统是一种基于银行或三方支付机构备付金账户&#xff0c;用于实现资金分配和结算的关键工具。它能够对交易过程中的资金进行准确的分配&#xff0c;确保每个参与者/合作伙伴按照规定的比例获得其应得的收益。本文将初步探讨分账系统的定义、功能、应用领域以及其在商业和金…

热门:最新植物大战僵尸杂交版张大仙主播同款

软件介绍: 植物大战僵尸杂交版是由B站UP主“潜艇伟伟迷”制作的一款结合了《植物大战僵尸》原有元素与创新玩法的游戏。这款游戏以其独特的“杂交”植物概念在B站上迅速走红&#xff0c;吸引了大量玩家的关注和讨论。在杂交版中&#xff0c;每个植物都有专属的特点以及玩法&am…

苍穹外卖环境搭建

一、前端环境搭建 ①整体结构 ②前端工程基于nginx运行 启动nginx:双击 nginx.exe 即可启动 nginx 服务&#xff0c;访问端口号为 80 进入浏览器地址输入locallhost回车 二、后端环境搭建 后端初始工程基于maven进行项目构建&#xff0c;并且进行分模块开发 (1) idea打开初始…

WordPress——Argon主题美化

文章目录 Argon主题美化插件类类别标签页面更新管理器文章头图URL查询监视器WordPress提供Markdown语法评论区头像设置发信设置隐藏登陆备份设置缓存插件 主题文件编辑器页脚显示在线人数备案信息(包含备案信息网站运行时间)banner下方小箭头滚动效果站点功能概览下方Links功能…

分布式并行策略

1.数据并行&#xff08;DP&#xff09; 将小批量分为n块&#xff0c;每个GPU拿到完整参数计算一块数据的梯度。&#xff08;通常性能会更好&#xff09; 假如一个批量有128个样本&#xff0c;然后有2个GPU&#xff0c;那么每个GPU可以拿到64个样本。&#xff08;每个GPU计算完…