承接上一篇关于模板的介绍,这次说说自动生成问题;程序员都是懒的,本人就是懒癌晚期……
思路
1.利用Xcode和我们自定义的工程模板生成项目
2.写json配置文件,在用脚本配合文件模板生成功能模块代码
3.利用xcodeproj添加文件引用
1.利用Xcode和我们自定义的工程模板生成项目
好的工程组织架构应该是一目了然的,当然也和作者的习惯有关,模板都是可以自定义的
2.写json配置文件,在用脚本配合文件模板生成功能模块代码
配置文件如下:
proj_path:工程文件的路径
parent_path:该模块的相对于工程文件的路径(本例:/Users/mac/Desktop/wwwww/wwwww/Module/Service)
moudels:需要添加的功能模块
完整架构如下

我的项目都是mvvm架构,功能上基本上都按照视图控制器来分,每个功能模块包含:Controller、Model、View三部分,如图所示
文件生成的工作就很简单了,挑选相应的模块,该换的换~
3.利用xcodeproj添加文件引用
再来就是添加文件引用了,需要用到ruby框架Xcodeproj,这个就是在cocoapods上使用的项目管理工具,很犀利…… 我们要做的就是写一个遍历脚本把相应的文件引用添加进工程即可,贴上我的脚本供参考一下:
1 require 'xcodeproj' 2 require 'json' 3 4 #移除索引 5 def removeBuildPhaseFilesRecursively(aTarget, aGroup) 6 aGroup.files.each do |file| 7 aTarget.resources_build_phase.remove_file_reference(file) 8 end 9 10 aGroup.groups.each do |group| 11 removeBuildPhaseFilesRecursively(aTarget, group) 12 end 13 end 14 15 #添加索引 16 def addFilesToGroup(aGroup, full_path, aTarget) 17 current_path = full_path 18 mGroup = aGroup 19 Dir.foreach(current_path) do |entry| 20 filePath = File.join(current_path, entry) 21 # 过滤目录和.DS_Store文件 22 if entry != ".DS_Store" && !filePath.to_s.end_with?(".meta") && entry != "." && entry != ".." then 23 if File::ftype(filePath) == "directory" 24 mGroup = aGroup.find_subpath(File.join(entry),true) 25 addFilesToGroup(mGroup,filePath,aTarget) 26 else 27 # 向group中增加文件引用 28 if nil == mGroup.find_subpath(entry) 29 fileReference = mGroup.new_reference(filePath) 30 aTarget.resources_build_phase.add_file_reference(fileReference, true) 31 end 32 end 33 end 34 end 35 end 36 37 fconfig = File.read('moudels.json') 38 configs = JSON.parse(fconfig) 39 for project_item in configs do 40 proj_path = project_item["proj_path"] 41 parent_path = project_item["parent_path"] 42 moudels = project_item["moudels"] 43 44 #相对于 ruby文件 .xcodeproj 的路径 45 project = Xcodeproj::Project.open(proj_path) 46 target = project.targets.first 47 project_dir = project.project_dir 48 target_name = target.name 49 50 for model in moudels do 51 moudel_name = model["moudel_name"] 52 moudel_path = "#{project_dir}/#{target_name}/#{parent_path}/#{moudel_name}" 53 mapiGroup = project.main_group.find_subpath(File.join(target.name, parent_path, moudel_name), true) 54 55 puts "mapiGroup : #{mapiGroup}" 56 puts "moudel_path : #{moudel_path}" 57 addFilesToGroup(mapiGroup, moudel_path,target) 58 end 59 60 61 puts "重组目录结构..." 62 project.save 63 end
嗯,就这样吧