开发环境:
- mac os x 10.11.1
- xcode 7.1.1
简述:
- 在实际开发过程中,我们经常会封装一些组件。那么,如何提高开发效率,不必每次都引入大量的文件呢?答案显然易见,那就是打成 framework 或者.a 包.
- 本篇将详细介绍如何将封装后的代码制作成 framework.
framework 是啥?
- framework 是一系列资源的集合,Xcode 可以方便的将这些文件编译到你的项目中去
开始建立 Framework
创建一个 Framework
建立一个简单的类,用于打印信息
#import <Foundation/Foundation.h> @interface SayHello : NSObject - (void)sayHello; @end
#import "SayHello.h" @implementation SayHello - (void)sayHello{ NSLog(@"Hello,Framework."); } @end
暴露头文件(你想让别人看到的)
选中工程->Build Phases->Headers,将头文件拖拽至 Public 中
多平台 Framework 支持
1.新建一个 Aggregate(集合)
New->Target->Aggregate
2.新建一个脚本
3.在脚本中键入如下代码
# Sets the target folders and the final framework product. # 如果工程名称和Framework的Target名称不一样的话,要自定义FMKNAME # 例如: FMK_NAME = "MyFramework" FMK_NAME=${PROJECT_NAME} # Install dir will be the final output to the framework. # The following line create it in the root folder of the current project. INSTALL_DIR=${SRCROOT}/Products/${FMK_NAME}.framework # Working dir will be deleted after the framework creation. WRK_DIR=build DEVICE_DIR=${WRK_DIR}/Release-iphoneos/${FMK_NAME}.framework SIMULATOR_DIR=${WRK_DIR}/Release-iphonesimulator/${FMK_NAME}.framework # -configuration ${CONFIGURATION} # Clean and Building both architectures. xcodebuild -configuration "Release" -target "${FMK_NAME}" -sdk iphoneos clean build xcodebuild -configuration "Release" -target "${FMK_NAME}" -sdk iphonesimulator clean build # Cleaning the oldest. if [ -d "${INSTALL_DIR}" ] then rm -rf "${INSTALL_DIR}" fi mkdir -p "${INSTALL_DIR}" cp -R "${DEVICE_DIR}/" "${INSTALL_DIR}/" # Uses the Lipo Tool to merge both binary files (i386 + armv6/armv7) into one Universal final product. lipo -create "${DEVICE_DIR}/${FMK_NAME}" "${SIMULATOR_DIR}/${FMK_NAME}" -output "${INSTALL_DIR}/${FMK_NAME}" rm -r "${WRK_DIR}" open "${INSTALL_DIR}"
此段脚本将为我们合并多平台的 framework,用于支持模拟器与真机.
注:
i386: 32位模拟器 x86_64: 64为模拟器 arm7: 在最老的支持iOS7的设备 arm7s: 在iPhone5和5C上使用 arm64: 运行于iPhone5S的64位ARM处理器
生成
选中 Aggregate,Command + B 编译工程
编译完成后,会自动打开编译完成的文件夹,Framework 就在那里.
快捷键:Command + 上(回到上级目录)
终于看到 Framework 啦~
检测多平台支持
进入 Framework 目录:cd framework 目录
lipo -info /目录/FrameworkTest.framework/FrameworkTest
结果
Architectures in the fat file: FrameworkTest.framework/FrameworkTest are: i386 x86_64 armv7 arm64
竟然不支持 armv7s,别急,有办法!
选中工程->BuildSetting 添加一条
再次编译,检查,Bingo~
整合到项目中
第一步
- 将生成的 framework Add 到你的项目中去
- 检查 framework 是否添加到项目中(Build Phases-Link Binary)
第二步
- 在工程中引入头文件
#import <FrameworkTest/SayHello.h>
第三步
- 使用你的 framework,测试打印信息
SayHello *hello = [[SayHello alloc] init]; [hello sayHello];
控制台打印结果:
2015-11-30 19:04:15.819 TeamTest03[14443:330569] Hello,Framework.
大功告成~
注:可能遇到的问题
- 运行时报错:image not found
问题描述:找不到 framework,framework 没有拷贝到 app 中
解决:选中工程->Build Phases-> 加号->New Copy File Phase
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于