Podfile 语法

1,435 阅读1分钟

cocoapod 是用ruby写的。在工程文件里执行 pod init 会生成Podfile文件,那么Podfile文件是怎么来下载依赖的库的呢?

target

target 'MyApp' do
  pod 'ObjectiveSugar', '~> 0.5'

  target 'MyAppTests' do
    inherit! :search_paths
    pod 'OCMock', '~> 2.0.1'
  end
end

target 是一个方法,do 后面相当与执行来一个block,在swift中相当于下面的形式,是不是形象来很多,swift的语法也是很简洁的。

func target(_ name: String , block: () -> () ) {
    // xxx
    block()
    //
}

target("MyApp") {
    pod ("ObjectiveSugar", "~> 0.5")
}

pod 中的冒号

pod 'AFNetworking', :path => '~/Documents/AFNetworking'
pod 'AFNetworking', :git => 'https://github.com/gowalla/AFNetworking.git', :tag => '0.7.0'

这里相当于 swift 中 pod("AFNetworking", [.path= "~/Documents/AFNetworking"]), => 是生成字典,path前面的冒号是ruby中一个symbol对象,可以理解为swift中的字符串枚举,如果要有多个值要用逗号隔开,比如

use_frameworks! 中的感叹号

这个表示使用动态库代替静态库,这里结尾的感叹号,其实没有意思,只是表示强调,ruby奇怪的语法。代码实现如下

def use_frameworks!(option = true)
    current_target_definition.use_frameworks!(option)
end

增加pod 执行前的处理

pre_install do |installer|
    # Do something fancy!
end

增加pod 执行后的处理

如果想pod执行完还要做一些事情,可以增加 post_install 函数,会增加一个block到执行完执行

post_install do |installer|
    installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
        config.build_settings['GCC_ENABLE_OBJC_GC'] = 'supported'
    end
    end
end

查看cocoapod 的源码,在这个文件cocoapods-core-1.10.1/lib/cocoapods-core/podfile/dsl.rb, 真是一个宝库,有很多功能

CocoaPods 都做了什么?这个文章讲的也蛮好的