podfile语法熟悉之post_install

4,137 阅读2分钟

在解决oclint错误的过程中,修改了podfile,改动如下

  post_install do |installer|
      installer.pods_project.targets.each do |target|
          target.build_configurations.each do |config|
              config.build_settings['COMPILER_INDEX_STORE_ENABLE'] = "NO"
          end
      end
  end

可是这段脚本是什么意思呢? 先熟悉下ruby语法

ruby中的迭代器

eg,下面是一个ruby的迭代器。

collection.each do |variable|
   code
end

所以

target.build_configurations.each do |config|
    config.build_settings['COMPILER_INDEX_STORE_ENABLE'] = "NO"
end

的意思是,获取target对象(ruby中万物皆对象)的构建配置(build_configurations)并遍历,从config中取出build_setting,这是一个哈希,类似于字典。设置COMPILER_INDEX_STORE_ENABLE 的值为NO

首先熟悉下ruby语法

Ruby中的方法

定义一个最简单的方法

//定义一个方法
def test
	puts "test"
end

//调用方法
test

定义一个带参数的方法

def sum(a,b)
	c = a+b
	puts c
end
//调用
sum 1,2

定义一个带默认参数的方法


def sum(a=1,b=2)
	c = a+b
	puts c
end

sum

ruby中的块

定义一个最简单的块

def testblock
	yield
end

testblock {puts 'hello world'}

可以看到我们传进去的是一个代码块,通过yield关键字可以调用传入的块

我们还可以给block增加参数

def testblock
	yield "张三"
end

testblock { |name| puts "#{name},你好!"}
//输出
张三,你好!

我们还可以将花括号换成do end

def testblock
	yield "李四"
end

testblock do |name| puts "#{name},你好!" end
//输出 
李四,你好!

让我们调整下代码的样子

testblock do |name| 
	puts "#{name},你好!" 
end

到这里,我们就搞懂了我们之前podfile里面写得代码了。

  post_install do |installer|
      installer.pods_project.targets.each do |target|
          target.build_configurations.each do |config|
              config.build_settings['COMPILER_INDEX_STORE_ENABLE'] = "NO"
          end
      end
  end
  • 调用了方法post_install,并传入了一个block作为参数
  • 方法post_install内部会调用传入的block,并给该block传入参数installer对象
  • Block内部的代码好懂,我们知道是一个迭代器,遍历所有的target,拿到target下面的构建配置,拿到build_settings,并修改配置COMPILER_INDEX_STORE_ENABLE 的值为NO

钩子函数的用处

除了post_install这个钩子函数,cocoapods中还有一个钩子函数,pre_install,这个钩子函数在允许我们在pod库已经下载了,但是还没有安装之前做一些事情,而post_install这个钩子函数允许我们在项目被写入硬盘之前做一些事情。

ruby中的哈希

类似于字典 创建哈希

H = Hash["a"=>100,"b":200]
puts "#{H['a']}"
//输出
100

引申

我们再回过头来看下一我们的podfile文件的内容,会更清晰

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
target 'testPrivatePod' do
  pod 'MBProgressHUD'
  pod 'TZImagePickerController'
  pod 'SDWebImage'
  pod 'PonyDebugger', :source => 'https://github.com/CocoaPods/Specs.git'

  post_install do |installer|
      installer.pods_project.targets.each do |target|
          target.build_configurations.each do |config|
              config.build_settings['COMPILER_INDEX_STORE_ENABLE'] = "NO"
          end
      end
  end
end

感觉都是调用的方法?