在对静态库和动态库的概念有了一定的理解之后,需要动手实践来巩固记忆,这篇文章将会很仔细的讲解只做一个.a静态库的过程。
1、构建项目-> 选择 “Cocoa Touch Static Library”

2、在一级目录加入目标文件,这里使用我封装的一个Toast类做为例子。

3、配置一下你的静态库工程,

4.设置需要暴露的.h文件
移除不想打包到.a中的多余文件

设置目标.h文件



5.选择编译环境,release,生成静态库


6.选择静态库目标环境,真机环境或者模拟器环境,建议选择真机,这样编译后.a文件才会变色,如果选择的是模拟器,即使编译通过了,.a文件也不会由红变黑,实际上是已经编译了模拟器的,只是xcode对模拟器编译过得静态库还是红色的,其实已经生成了.a文件

comand+B然后可以看到libStaticLibTest.a已经变成黑色,然后show in finder即可
6.静态库的使用
以前几步制作的libStaticLibTest.a为例一下静态库的使用
在新工程中导入已经编辑好的.a文件和头文件

#import "ViewController.h"
#import "FGToast.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[FGToast showTips:@"测试成功"];
}
运行效果:
7.模拟器.a和真机.a的合并使用,支持真机和模拟器。注意:合并后的.a体积大约是单独包的2倍左右。
- 按照之前步骤,编译一个模拟器环境的.a

- 新建一个文件夹,将两个.a扔进去

- 进行合并操作
- 在终端输入:
➜ ~ lipo -create /Users/Fengur/Desktop/StaticLib/Release-iphonesimulator/libStaticLibTest.a /Users/Fengur/Desktop/StaticLib/Release-iphoneos/libStaticLibTest.a -output /Users/Fengur/Desktop/StaticLib/StaticTestCombine.a
lipo -create simulator.a(路径) iphone.a(路径) -output 输出路径(包含合并后.a名称)
- 合并完成,使用合并后的.a即可

- Demo代码与效果
#import "ViewController.h"
#import "FGToast.h"
#if TARGET_IPHONE_SIMULATOR
#define SIMULATOR @"模拟器"
#elif TARGET_OS_IPHONE
#define SIMULATOR @"真机"
#endif
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[FGToast showTips:[NSString stringWithFormat:@"!!%@!!测试效果",SIMULATOR]];
}

8.以上测试工程 传送门 Demo中有三个工程:
- StaticLibTest 为生产静态库工程
- StaticVerify 为单独真机静态库效果
- CombineStaticLibVerify 为合并静态库效果
9.有错误或者补充,敬请提醒。
网友评论