公司突然给了个需求,要把另一个项目整合到当前的项目里面,说是大部分页面代码共用少部分差别。后来我想了想,这个需求理论上是可以做的,但是要看两个项目的差别多大,其次!代码写得是不是很规范,耦合性高不高,在我看来我接手的项目代码写得很乱所以不赞成的,但是上面的要求,我还是去研究了一下具体的实现方案。
就如标题所说的,多个target的创建和一些配置而已,直接上图:
①直接复制,会在下方多出一个 同名+copy 的target
![](https://upload-images.jianshu.io/upload_images/10845361-77e162e7d5afb8cc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
②双击修改名称成你想要的名字
③添加宏定义
④同样,在原来的target添加宏定义,值=0,(注意debug和release一起加)
![](https://upload-images.jianshu.io/upload_images/10845361-8527540db3e9f91c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
⑤修改bundleIdentifier和displayName。
![](https://upload-images.jianshu.io/upload_images/10845361-308c2124e0536480.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
⑥修改启动图和icon。
![](https://upload-images.jianshu.io/upload_images/10845361-65951b393e62d5d2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
⑦在pch文件使用
![](https://upload-images.jianshu.io/upload_images/10845361-e8d0c1e5bd3d469c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
⑧在.m文件代码中使用(我这是AppDelegate里面的didFinsh方法里面,在这里控制keywindow等就可以控制根试图,首页等差别文件)
![](https://upload-images.jianshu.io/upload_images/10845361-4f40dad77e1945fb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
⑨切换target运行,可以发现导入的头文件和.m文件的输出和预期一样。
![](https://upload-images.jianshu.io/upload_images/10845361-ac9324c29f335e6a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
⑩新建文件的时候或者拖入文件的时候记得选择合适的target,谁需要用到这个文件就选谁,都需要就全选(全部全选的话,应该会给编译带来弊端)
![](https://upload-images.jianshu.io/upload_images/10845361-3075729857a1d9d1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
*顺便说一下,新建一个目录来管理另一个target的专属文件,也就是差异文件,使项目结构清晰易读。
![](https://upload-images.jianshu.io/upload_images/10845361-c9263b2d2bbd0fc9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
*还有target也是可以直接点击+号新建的,这样建出来的target会附带很多文件
![](https://upload-images.jianshu.io/upload_images/10845361-7c93a432f4376b5c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
可以看到,跟全新的项目一样,需要慢慢配置,我没去仔细研究,有兴趣的自己试试
![](https://upload-images.jianshu.io/upload_images/10845361-f6729ad69451f166.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最后,理解了这层作用以后,以后新写的项目尽量把这个问题考虑进去,代码封装好一些,耦合性低,复用性高,方便以后扩展。
原文 https://www.jianshu.com/p/ae0c9726785e