0x00 尝试
看这位大佬的文章<记录启动速度优化30%的过程>, 就去尝试一下在自己的项目中, 尝试后发现效果还是有的很不错, 就是对静态库动态库知识有一些要求~遇到了很多坑, 只有一个很重要
使用私有库组件, 组件里有 xib 资源, 会遇到找不到资源的问题, 导致闪退
Could not load NIB in bundle
0x01 解决
-
首先将 xib 文件都放在一个文件夹, 然后从
Development Pods
中删除 -
把 Xib 文件夹放到
Classes
中, 不能放到Assets
, 如果放在Assets
会把源文件也导入 bundle 中, 会被别人看到 -
然后将 Xib 文件夹 拖入 工程
Development Pods\组件名字的文件夹\
如下选择
-
这样在 bundle 中就有了索引, 最后在
.podspec
文件中修改s.resource_bundles
数组中的目录, 把 Xib 文件夹的路径写入数组中, 写入后 pod install 一下 demo 资源文件就如第二个图一样 -
到此资源引入问题就解决了, 还有代码问题需要处理,
Bundle
在静态库的时候其实就是MainBundle
, 而在动态库并不是MainBundle
, 动态库是 framework 下的结构, 需要Bundle(for: 类名.self)
来获取实际的 bundle -
注意: 静态库的时候
Bundle(for: 类名.self)
获取到的就是MainBundle
, 所以通过这个来区分是静态库还是动态库, 这样组件里面使用xibBundle
就可以访问实际 bundle -
以下是获取 bundle 的代码
extension Bundle {
static var currentBundle: Bundle {
Bundle(for: CommonAlertViewController.self)
}
static var xibBundle: Bundle {
if Bundle.main == currentBundle,
let bundle = Bundle(path: currentBundle.path(forResource: "\(CommonAlertViewController.self)", ofType: "bundle") ?? "") {
return bundle
}
return currentBundle
}
static var assetBundle: Bundle {
if let bundle = Bundle(path: currentBundle.path(forResource: "\(CommonAlertViewController.self)", ofType: "bundle") ?? "") {
return bundle
}
return currentBundle
}
}
网友评论