<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Liu Edmond on Medium]]></title>
        <description><![CDATA[Stories by Liu Edmond on Medium]]></description>
        <link>https://medium.com/@liuedmond?source=rss-d3b3aa852ef3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*td8hxHQ6P4H3o4RR.jpg</url>
            <title>Stories by Liu Edmond on Medium</title>
            <link>https://medium.com/@liuedmond?source=rss-d3b3aa852ef3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:37:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liuedmond/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[1. 版本管理工具及 Ruby 工具链环境]]></title>
            <link>https://medium.com/@liuedmond/1-%E7%89%88%E6%9C%AC%E7%AE%A1%E7%90%86%E5%B7%A5%E5%85%B7%E5%8F%8A-ruby-%E5%B7%A5%E5%85%B7%E9%93%BE%E7%8E%AF%E5%A2%83-c057cb026b49?source=rss-d3b3aa852ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c057cb026b49</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cocoapods]]></category>
            <category><![CDATA[package-management]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Liu Edmond]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-08-21T05:14:05.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*7ojh9jMbAE5fIrMn" /></figure><blockquote><strong><em>CocoaPods 历险记</em></strong><em>这个专题是 </em><strong><em>Edmond</em></strong><em> 和 </em><strong><em>冬瓜</em></strong><em> 是对于 iOS / macOS 工程中版本管理工具 CocoaPods 的实现细节、原理、源码、实践与经验的分享记录，旨在帮助大家能够更加了解这个依赖管理工具，而不仅局限于 </em><em>pod install 和 </em><em>pod update 。</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HXoZK0WAUTAAqht5.png" /></figure><p>CocoaPods 作为业界标准，各位 iOS 开发同学应该都不陌生。不过很多同学对 CocoaPods 的使用基本停留在 pod install 和 pod update 上。一旦项目组件化，各业务线逻辑拆分到独立的 Pod 中后，光了解几个简单 Pod 命令是无法满足需求的，同时还面临开发环境的一致性， Pod 命令执行中的各种异常错误，都要求我们对其有更深层的认知和 🤔。</p><p>关于 CocoaPods 深入的文章有很多，推荐 ObjC China 的这篇， <a href="https://objccn.io/issue-6-4/">深入理解 CocoaPods</a>，而本文希望从依赖管理工具的角度来谈谈 CocoaPods 的管理理念。</p><blockquote><em>Version control systems are a category of software tools that help a software team manage changes to source code over time. Version control software keeps track of every modification to the code in a special kind of database.</em></blockquote><p>软件工程中，版本控制系统是敏捷开发的重要一环，为后续的持续集成提供了保障。 Source Code Manager (SCM) 源码管理就属于 VCS 的范围之中，熟知的工具有如 Git 。而 CocoaPods 这种针对各种语言所提供的 Package Manger (PM) 也可以看作是 SCM 的一种。</p><p>而像 Git 或 SVN 是针对项目的单个文件的进行版本控制，而 PM 则是以每个独立的 Package 作为最小的管理单元。包管理工具都是结合 SCM 来完成管理工作，对于被 PM 接管的依赖库的文件，通常会在 Git 的 .ignore 文件中选择忽略它们。</p><h3>Git Submodule</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*erGDMf45wN8eMlup.png" /></figure><blockquote><em>Git submodules allow you to keep a git repository as a subdirectory of another git repository. Git submodules are simply a reference to another repository at a particular snapshot in time. Git submodules enable a Git repository to incorporate and track version history of external code.</em></blockquote><p><strong>Git Submodules 可以算是 PM 的&quot;青春版&quot;，它将单独的 git 仓库以子目录的形式嵌入在工作目录中</strong>。它不具备 PM 工具所特有的 <a href="https://semver.org/">语义化版本</a> 管理、无法处理依赖共享与冲突等。只能保存每个依赖仓库的文件状态。</p><p>Git 在提交更新时，会对所有文件制作一个快照并将其存在数据库中。Git 管理的文件存在 3 种状态：</p><ul><li><strong>working director：</strong> 工作目录，即我们肉眼可见的文件</li><li><strong>stage area：</strong> 暂存区 (或称 index area )，存在 .git/index 目录下，保存的是执行 git add 相关命令后从工作目录添加的文件。</li><li><strong>commit history：</strong> 提交历史，存在 .git/ 目录下，到这个状态的文件改动算是入库成功，基本不会丢失了。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/0*qXhRWtkPgwhliWYI.jpeg" /></figure><p>Git submodule 是依赖 .gitmodules 文件来记录子模块的。</p><pre>[submodule &quot;ReactNative&quot;]<br>	path = ReactNative<br>	url = https://github.com/facebook/ReactNative.git</pre><h3>Package Manger</h3><p>作为 Git Submodule 的强化版，PM 基本都具备了语义化的版本检查能力，依赖递归查找，依赖冲突解决，以及针对具体依赖的构建能力和二进制包等。简单对比如下：</p><p>从 👆 可见，PM 工具基本围绕这个两个文件来现实包管理：</p><pre>| Key File  | Git submodule  |   CocoaPods   |        SPM        |        npm         |<br>|:--------: |:-------------: |:------------: |:----------------: |:-----------------: |<br>| 描述文件  | .gitmodules    | Podfile       | Package.swift     | Package.json       |<br>| 锁存文件  | .git/modules   | Podfile.lock  | Package.resolved  | package-lock.json  |</pre><ul><li><strong>描述文件</strong>：声明了项目中存在哪些依赖，版本限制；</li><li><strong>锁存文件（Lock 文件）</strong>：记录了依赖包最后一次更新时的全版本列表。</li></ul><p>除了这两个文件之外，中心化的 PM 一般会提供依赖包的托管服务，比如 npm 提供的 <a href="https://www.npmjs.com/">npmjs.com</a> 可以集中查找和下载 npm 包。如果是去中心化的 PM 比如 iOS 的 Carthage 和 SPM 就只能通过 Git 仓库的地址了。</p><h3>CocoaPods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yNgOteYzRjVwo8kW.png" /></figure><p><strong>CocoaPods 是开发 iOS/macOS 应用程序的一个第三方库的依赖管理工具。</strong> 利用 CocoaPods，可以定义自己的依赖关系（简称 Pods ），以及在整个开发环境中对第三方库的版本管理非常方便。</p><p>下面我们以 CocoaPods 为例。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*DRxXlPY_sVBYfCQT" /></figure><h4>Podfile</h4><p>Podfile 是一个文件，以 DSL（其实直接用了 Ruby 的语法）来描述依赖关系，用于定义项目所需要使用的第三方库。该文件支持高度定制，你可以根据个人喜好对其做出定制。更多相关信息，请查阅 <a href="http://guides.cocoapods.org/syntax/podfile.html">Podfile 指南</a> 。</p><h4>Podfile.lock</h4><p>这是 CocoaPods 创建的最重要的文件之一。它记录了需要被安装的 Pod 的每个已安装的版本。如果你想知道已安装的 Pod 是哪个版本，可以查看这个文件。推荐将 Podfile.lock 文件加入到版本控制中，这有助于整个团队的一致性。</p><h4>Manifest.lock</h4><p>这是每次运行 pod install 命令时创建的 Podfile.lock 文件的副本。如果你遇见过这样的错误 <strong>沙盒文件与 </strong><strong>Podfile.lock 文件不同步 (The sandbox is not in sync with the </strong><strong>Podfile.lock)</strong>，这是因为 Manifest.lock 文件和 Podfile.lock 文件不一致所引起。由于 Pods 所在的目录并不总在版本控制之下，这样可以保证开发者运行 App 之前都能更新他们的 Pods ，否则 App 可能会 crash，或者在一些不太明显的地方编译失败。</p><h3>Master Specs Repo</h3><blockquote><em>Ultimately, the goal is to improve discoverability of, and engagement in, third party open-source libraries, by creating a more centralized ecosystem.</em></blockquote><p>作为包管理工具， CocoaPods 的目标是为我们提供一个更加集中的生态系统，来提高依赖库的可发现性和参与度。本质上是为了提供更好的检索和查询功能，可惜成为了它的问题之一。因为 CocoaPods 通过官方的 Spec 仓库来管理这些注册的依赖库。随着不断新增的依赖库导致 Spec 的更新和维护成为了使用者的包袱。</p><p>好在这个问题在 1.7.2 版本中已经解决了， CocoaPods 提供了 <a href="http://blog.cocoapods.org/CocoaPods-1.7.2/">Mater Repo CDN</a> ，可以直接 CDN 到对应的 Pod 地址而无需在通过本地的 Spec 仓库了。同时在 1.8 版本中，官方默认的 Spec 仓库已替换为 CDN，其地址为 <a href="https://cdn.cocoapods.org/">https://cdn.cocoapods.org</a> 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Og64MQjw-zc2vbbK" /></figure><p>我们知道 CocoaPods 是通过 Ruby 语言实现的。它本身就是一个 Gem 包。理解了 Ruby 的依赖管理有助于我们更好的管理不同版本的 CocoaPods 和其他 Gem 。同时能够保证团队中的所有同事的工具是在同一个版本，这也算是敏捷开发的保证吧。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TH8Y2wN_l0mW7HRI.png" /></figure><p><a href="https://rvm.io/"><strong>RVM</strong></a><strong> 和 </strong><a href="https://github.com/rbenv/rbenv"><strong>rbenv</strong></a><strong> 都是管理多个 Ruby 环境的工具，它们都能提供不同版本的 Ruby 环境管理和切换。</strong></p><blockquote><strong><em>具体哪个更好要看个人习惯。</em></strong><em> 当然 </em><em>rbenv 官方是这么说的 </em><a href="https://github.com/rbenv/rbenv/wiki/Why-rbenv%3F"><em>Why rbenv</em></a><em> 。本文后续的实验也都是是使用 </em><em>rbenv 进行演示。</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-PTlP4nto6Nx5hT0" /></figure><h3>RubyGems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*5bMix7RVX3CHlees.png" /></figure><blockquote><em>The RubyGems software allows you to easily download, install, and use ruby software packages on your system. The software package is called a “gem” which contains a packaged Ruby application or library.</em></blockquote><p><a href="https://rubygems.org/"><strong>RubyGems</strong></a><strong> 是 Ruby 的一个包管理工具，这里面管理着用 Ruby 编写的工具或依赖我们称之为 Gem。</strong></p><p>并且 RubyGems 还提供了 Ruby 组件的托管服务，可以集中式的查找和安装 library 和 apps。当我们使用 gem install xxx 时，会通过 rubygems.org 来查询对应的 Gem Package。而 iOS 日常中的很多工具都是 Gem 提供的，例： Bundler， fastlane， jazzy， CocoaPods 等。</p><p>在默认情况下 Gems 总是下载 library 的最新版本，这无法确保所安装的 library 版本符合我们预期。因此我们还缺一个工具。</p><h3>Bundler</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*dbNEjiEk0sF_CSzM.png" /></figure><p><a href="https://bundler.io/"><strong>Bundler</strong></a><strong> 是管理 Gem 依赖的工具，可以隔离不同项目中 Gem 的版本和依赖环境的差异，也是一个 Gem。</strong></p><p>Bundler 通过读取项目中的依赖描述文件 Gemfile ，来确定各个 Gems 的版本号或者范围，来提供了稳定的应用环境。当我们使用 bundle install 它会生成 Gemfile.lock 将当前 librarys 使用的具体版本号写入其中。之后，他人再通过 bundle install 来安装 libaray 时则会读取 Gemfile.lock 中的 librarys、版本信息等。</p><p><strong>可以说 </strong><strong>CocoaPods 其实是 iOS 版的 RubyGems + Bundler 组合。Bundler 依据项目中的 </strong><strong>Gemfile 文件来管理 Gem，而 </strong><strong>CocoaPods 通过 Podfile 来管理 Pod。</strong></p><p><a href="https://bundler.io/v2.0/gemfile.html">Gemfile</a> 配置如下：</p><pre>source &#39;https://gems.example.com&#39; do<br>  gem &#39;cocoapods&#39;, &#39;1.8.4&#39;是管理 Gem 依赖的工具<br>  gem &#39;another_gem&#39;, :git =&gt; &#39;https://looseyi.github.io.git&#39;, :branch =&gt; &#39;master&#39;<br>end</pre><p>可见，Podfile 的 DSL 写法和 Gemfile 如出一辙。那什么情况会用到 Gemfile 呢 ？</p><p>CocoaPods 每年都会有一些重大版本的升级，前面聊到过 CocoaPods 在 install 过程中会对项目的 .xcodeproj 文件进行修改，不同版本其有所不同，这些在变更都可能导致大量 conflicts，处理不好，项目就不能正常运行了。我想你一定不愿意去修改 .xcodeproj 的冲突。</p><p>如果项目是基于 fastlane 来进行持续集成的相关工作以及 App 的打包工作等，也需要其版本管理等功能。</p><p>讲完了这些工具的分工，然后来说说实际的运用。 <strong>我们可以使用 </strong><strong>homebrew + </strong><strong>rbenv + </strong><strong>RubyGems + </strong><strong>Bundler 这一整套工具链来控制一个工程中 Ruby 工具的版本依赖。</strong></p><p>以下是我认为比较可控的 Ruby 工具链分层管理图。下面我们逐一讲述每一层的管理方式，以及实际的操作方法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oq93p44MzY__EqzG.png" /></figure><h3>1. 使用 homebrew 安装 rbenv</h3><pre>$ brew install rbenv</pre><p>安装成功后输入 rbenv 就可以看到相关提示：</p><pre>$ rbenv<br><br>rbenv 1.1.2<br>Usage: rbenv &lt;command&gt; [&lt;args&gt;]<br><br>Some useful rbenv commands are:<br>   commands    List all available rbenv commands<br>   local       Set or show the local application-specific Ruby version<br>   global      Set or show the global Ruby version<br>   shell       Set or show the shell-specific Ruby version<br>   install     Install a Ruby version using ruby-build<br>   uninstall   Uninstall a specific Ruby version<br>   rehash      Rehash rbenv shims (run this after installing executables)<br>   version     Show the current Ruby version and its origin<br>   versions    List installed Ruby versions<br>   which       Display the full path to an executable<br>   whence      List all Ruby versions that contain the given executable<br><br>See `rbenv help &lt;command&gt;&#39; for information on a specific command.<br>For full documentation, see: https://github.com/rbenv/rbenv#readme</pre><h3>2. 使用 rbenv 管理 Ruby 版本</h3><p>使用 rbenv 来安装一个 Ruby 版本，这里我使用刚刚 release Ruby 2.7：</p><pre>$ rbenv install 2.7.0</pre><p>这个安装过程有些长，因为要下载 openssl 和 Ruby 的解释器，大概要 20 分钟左右。</p><p>安装成功后，我们让其在本地环境中生效：</p><pre>$ rbenv shell 2.7.0</pre><blockquote><em>输入上述命令后，可能会有报错。 </em><em>rbenv 提示我们在 </em><em>.zshrc 中增加一行 </em><em>eval &quot;$(rbenv init -)&quot; 语句来对 </em><em>rbenv 环境进行初始化。如果报错，我们增加并重启终端即可。</em></blockquote><pre>$ ruby --version<br>ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]<br>$ which ruby<br>/Users/gua/.rbenv/shims/ruby</pre><p>切换之后我们发现 Ruby 已经切换到 rbenv 的管理版本，并且其启动 PATH 也已经变成 rbenv 管理下的 Ruby。并且我们可以看一下 Ruby 捆绑的 Gem 的 PATH ：</p><pre>$ which gem<br>/Users/bytedance/.rbenv/shims/gem</pre><h3>3. 查询系统级 Gem 依赖</h3><p>如此，我们使用 rbenv 已经对 Ruby 及其 Gem 环境在版本上进行了环境隔离。我们可以通过 gem list 命令来查询当前系统环境下所有的 Gem 依赖：</p><pre>$ gem list<br><br>*** LOCAL GEMS ***<br><br>activesupport (4.2.11.3)<br>...<br>claide (1.0.3)<br>cocoapods (1.9.3)<br>cocoapods-core (1.9.3)<br>cocoapods-deintegrate (1.0.4)<br>cocoapods-downloader (1.3.0)<br>cocoapods-plugins (1.0.0)<br>cocoapods-search (1.0.0)<br>cocoapods-stats (1.1.0)<br>cocoapods-trunk (1.5.0)<br>cocoapods-try (1.2.0)</pre><p>记住这里的 CocoaPods 版本，我们后面项目中还会查询。</p><p>如此我们已经完成了全部的 Ruby、Gem 环境的配置，我们通过一张漏斗图再来梳理一下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IPSs1E-l_VmtxUAV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VspJMg5WLp-nq1wm.png" /></figure><p>以下也会逐一讲述每一层的管理方式，以及实际的操作方法。</p><h4>1. 在 iOS 工程中初始化 Bundler 环境</h4><p>首先我们有一个 iOS Demo 工程 — GuaDemo ：</p><pre>$ ls -al<br>total <strong>0</strong><br>drwxr-xr-x   <strong>4</strong> gua  staff   <strong>128</strong> Jun <strong>10</strong> 14:47 .<br>drwxr-xr-x@ <strong>52</strong> gua  staff  <strong>1664</strong> Jun <strong>10</strong> 14:47 ..<br>drwxr-xr-x   <strong>8</strong> gua  staff   <strong>256</strong> Jun <strong>10</strong> 14:47 GuaDemo<br>drwxr-xr-x@  <strong>5</strong> gua  staff   <strong>160</strong> Jun <strong>10</strong> 14:47 GuaDemo.xcodeproj</pre><p>首先先来初始化一个 Bundler 环境（其实就是自动创建一个 Gemfile 文件）：</p><pre>$ bundle init<br><br>Writing new Gemfile to /Users/Gua/GuaDemo/Gemfile</pre><h4>2. 在 Gemfile 中声明使用的 CocoaPods 版本并安装</h4><p>之后我们编辑一下这个 Gemfile 文件，加入我们当前环境中需要使用 CocoaPods 1.5.3 这个版本，则使用 Gemfile 的 DSL 编写以下内容：</p><pre><em># frozen_string_literal: true</em><br><br>source &quot;https://rubygems.org&quot;<br><br>git_source(:github) {|repo_name| &quot;https://github.com/#{repo_name}&quot; }<br><br><em># gem &quot;rails&quot;</em><br>gem &quot;cocoapods&quot;, &quot;1.5.3&quot;</pre><p>编写之后执行一下 bundle install ：</p><pre>$ bundle install<br>Fetching gem metadata from https://gems.ruby-china.com/............<br>Resolving dependencies...<br>...<br>Fetching cocoapods <strong>1</strong>.<strong>5</strong>.<strong>3</strong><br>Installing cocoapods <strong>1</strong>.<strong>5</strong>.<strong>3</strong><br>Bundle complete! <strong>1</strong> Gemfile dependency, <strong>30</strong> gems now installed.</pre><p>发现 CocoaPods 1.5.3 这个指定版本已经安装成功，并且还保存了一份 Gemfile.lock 文件用来锁存这次的依赖结果。</p><h4>3. 使用当前环境下的 CocoaPods 版本操作 iOS 工程</h4><p>此时我们可以检查一下当前 Bundler 环境下的 Gem 列表：</p><pre>$ bundle exec gem list<br><br>*** LOCAL GEMS ***<br><br>activesupport (<strong>4</strong>.<strong>2</strong>.<strong>11</strong>.<strong>3</strong>)<br>atomos (<strong>0</strong>.<strong>1</strong>.<strong>3</strong>)<br>bundler (<strong>2</strong>.<strong>1</strong>.<strong>4</strong>)<br>CFPropertyList (<strong>3</strong>.<strong>0</strong>.<strong>2</strong>)<br>claide (<strong>1</strong>.<strong>0</strong>.<strong>3</strong>)<br>cocoapods (<strong>1</strong>.<strong>5</strong>.<strong>3</strong>)<br>...</pre><p>发现相比于全局 Gem 列表，这个列表精简了许多，并且也只是基础 Gem 依赖和 CocoaPods 的 Gem 依赖。此时我们使用 bundle exec pod install 来执行 Install 这个操作，就可以使用 CocoaPods 1.5.3 版本来执行 Pod 操作了（当然，前提是你还需要写一个 Podfile ，大家都是 iOSer 这里就略过了）。</p><pre>$ bundle exec pod install Analyzing dependencies Downloading dependencies Installing SnapKit (<strong>5</strong>.<strong>0</strong>.<strong>1</strong>) Integrating client project [!] Please close any current Xcode sessions and use `GuaDemo.xcworkspace` for this project from now on. Sending stats Pod installation complete! There is <strong>1</strong> dependency from the Podfile and <strong>1</strong> total pod installed.</pre><p>可以再来看一下 Podfile.lock 文件：</p><pre>cat Podfile.lock<br>PODS:<br>  - SnapKit (<strong>5</strong>.<strong>0</strong>.<strong>1</strong>)<br><br>DEPENDENCIES:<br>  - SnapKit (~&gt; <strong>5</strong>.<strong>0</strong>.<strong>0</strong>)<br><br>SPEC REPOS:<br>  https://github.com/cocoapods/specs.git:<br>    - SnapKit<br><br>SPEC CHECKSUMS:<br>  SnapKit: <strong>97</strong>b92857e3df3a0c71833cce143274bf6ef8e5eb<br><br>PODFILE CHECKSUM: <strong>1</strong>a4b05aaf43554bc31c90f8dac5c2dc0490203e8<br><br>COCOAPODS: <strong>1</strong>.<strong>5</strong>.<strong>3</strong></pre><p>发现使用的 CocoaPods 的版本确实是 1.5.3 。而当我们不使用 bundle exec 执行前缀，则会使用系统环境中的 CocoaPods 版本。如此我们也就验证了工程中的 Gem 环境和系统中的环境可以通过 Bundler 进行隔离。</p><h3>总结</h3><ul><li>通过版本管理工具演进的角度可以看出，CocoaPods 的诞生并非一蹴而就，也是不断地借鉴其他管理工具的优点，一点点的发展起来的。VCS 工具从早期的 SVN、Git，再细分出 Git Submodule，再到各个语言的 Package Manager 也是一直在发展的。</li><li>虽然 CocoaPods 作为包管理工具控制着 iOS 项目的各种依赖库，但其自身同样遵循着严格的版本控制并不断迭代。希望大家可以从本文中认识到版本管理的重要性。</li><li>通过实操 Bundler 管理工程的全流程，学习了 Bundler 基础，并学习了如何控制一个项目中的 Gem 版本信息。</li></ul><p>后续我们将会围绕 CocoaPods ，从工具链逐渐深入到细节，根据我们的使用经验，逐一讲解。</p><h3>知识点问题梳理</h3><p>这里罗列了四个问题用来考察你是否已经掌握了这篇文章，如果没有建议你加入 <strong>收藏</strong> 再次阅读：</p><ol><li>PM 是如何进行依赖库的版本管理？</li><li>Ruby 和 RVM/rbenv 之间的关系是什么？</li><li>Gem、Bundler 和 CocaPods 之间的关系是什么？</li><li>如何通过 Bundler 来管理工程中的 Gem 环境？如何锁死工程内部的 CocoaPods 版本？</li></ol><p><em>Originally published at </em><a href="https://looseyi.github.io/post/sourcecode-cocoapods/01-cocoapods-tour/"><em>https://looseyi.github.io</em></a><em> on June 10, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c057cb026b49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[源码浅析 — CocoaLumberjack 3.6 之 DDLog]]></title>
            <link>https://medium.com/@liuedmond/%E6%BA%90%E7%A0%81%E6%B5%85%E6%9E%90-cocoalumberjack-3-6-%E4%B9%8B-ddlog-13b7c926e57d?source=rss-d3b3aa852ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b7c926e57d</guid>
            <category><![CDATA[cocoalumberjack]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[log4j]]></category>
            <category><![CDATA[logging-system]]></category>
            <category><![CDATA[ddlog]]></category>
            <dc:creator><![CDATA[Liu Edmond]]></dc:creator>
            <pubDate>Mon, 04 May 2020 10:20:00 GMT</pubDate>
            <atom:updated>2020-05-14T11:15:46.249Z</atom:updated>
            <content:encoded><![CDATA[<h3>源码浅析 — CocoaLumberjack 3.6 之 DDLog</h3><blockquote><strong><em>CocoaLumberjack</em></strong><em> is a fast &amp; simple, yet powerful &amp; flexible logging framework for Mac and iOS.</em></blockquote><p>先扯一下 lumberjack 这个单词，对应的就是它的 logo，一位伐木工，好想知道作者对用意啊，是基础建设的意思吗？</p><p>写这篇文章的理由并非心血来潮，而是最近在使用过程中偶然发现，它居然有这么多隐藏功能，尽管项目里引入也有好多年了。接着又看了一下官方提供的 demos， 简直是惊呆了（也太丰富了吧，强烈建议各位看看官方 Demo）。最后，因为国内基本都是关于它的使用介绍，本文希望能从代码的角度来看看它的一些设计和🤔。最后会介绍一下它所支持的扩展。</p><h3>Document</h3><p>作为历史悠久的 library，它的 <a href="https://github.com/CocoaLumberjack/CocoaLumberjack/tree/master/Documentation">document</a> 还是非常详细的，分三级：</p><ul><li><strong>Beginner 入门级</strong>：<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/GettingStarted.md">使用说明</a>、<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomFormatters.md">自定义日志格式</a>、<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/Performance.md">性能测试</a>、支持<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/XcodeColors.md">彩色输出</a>等；</li><li><strong>Intermediate 进阶</strong>：lumberjack <a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/Architecture.md">内部概述</a>，如何定制 <a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomContext.md">custom logging context</a>、<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomLoggers.md">custrom logger</a>、<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomLogLevels.md">custom log levels</a> 等；</li><li><strong>Advanced 高阶</strong>：<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/DynamicLogLevels.md">动态修改 log levels</a>、<a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/LogFileManagement.md">log 文件管理（压缩、上传</a>。</li></ul><p>照例，我们先预览一下类图，有个大概的印象。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6iTXya1uYjrbfxU0.jpg" /></figure><p>在梳理完脑图才发现官方其实提供了完整的 UML 图。不过既然整理了脑图，那我把它贴在文末。</p><p>UML 上直观感受就是 class 并不多，但是功能确实十分完善，我们一点点来看看。</p><h3>DDLog</h3><p>本文默认你是经历过新手村的，如果对 Lumberjack 的 API 完全不熟悉，请挪步： <a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/GettingStarted.md">getting start</a> 。</p><p>核心文件 DDLog.h 中有声明了最重要的两个协议 <strong>DDLoger</strong> 和 <strong>DDLogFormatter</strong>，而 <strong>DDLog</strong> class 可以看作是一个 manager 的存在，它管理着所有注册在案的 loogers 和 formatters。这三个对于正常项目来说已经完全够用了。我们就从 protocol 着手，最后来说这个 DDLog。</p><h4>Loggers</h4><blockquote><em>A logger is a class that does something with a log message. The lumberjack framework comes with several different loggers. (You can also </em><a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomLoggers.md"><em>create your own</em></a><em>.) Loggers such as </em><em>DDOSLogger can be used to duplicate the functionality of </em><em>NSLog. And </em><em>DDFileLogger can be used to write log messages to a log file.</em></blockquote><p>loggers 相关类主要是对 log message 进行加工处理。那么一条 DDLogMessage 会存有哪些可用信息呢？</p><h4>DDLogMessage</h4><blockquote><em>Used by the logging primitives. (And the macros use the logging primitives.)</em></blockquote><p>log message 用于记录日志原语，它是通过宏来实现的。logging primitives 是什么意思呢？可以理解为 log message 保存了 log 被调用时的一系列相关环境的上下文。单词 primitive 一开始没看明白，不过计算机中倒是有一个 <a href="https://baike.baidu.com/item/%E5%8E%9F%E8%AF%AD">原语</a> 的概念（不一定对），可以帮助大家理解这个单词。</p><p>具体存了哪些东西呢？</p><pre>@interface DDLogMessage : NSObject &lt;NSCopying&gt;<br>{<br>    <em>// Direct accessors to be used only for performance<br></em>    @public<br>    NSString *_message;<br>    DDLogLevel _level;<br>    DDLogFlag _flag;<br>    NSInteger _context;<br>    NSString *_file;<br>    NSString *_fileName;<br>    NSString *_function;<br>    NSUInteger _line;<br>    <strong>id</strong> _tag;<br>    DDLogMessageOptions _options;<br>    NSDate * _timestamp;<br>    NSString *_threadID;<br>    NSString *_threadName;<br>    NSString *_queueLabel;<br>    NSUInteger _qos;<br>}</pre><p>这里通过前置声明实例变量，这样调用方可以避开 getter 直接访问变量，来提高访问效率。当然作者也提供了 readonly 的 @property method。</p><p>首先，message、file、function <strong>默认不会执行 copy 操作</strong> ，如果需要可以通过 DDLogMessageOptions 来控制：</p><pre>typedef NS_OPTIONS(NSInteger, DDLogMessageOptions){<br>	 <em>/// Use this to use a copy of the file path<br></em>    DDLogMessageCopyFile        = <strong>1</strong> &lt;&lt; <strong>0</strong>,<br> 	 <em>/// Use this to use a copy of the function name<br></em>    DDLogMessageCopyFunction    = <strong>1</strong> &lt;&lt; <strong>1</strong>,<br>	 <em>/// Use this to use avoid a copy of the message<br></em>    DDLogMessageDontCopyMessage = <strong>1</strong> &lt;&lt; <strong>2</strong><br>};</pre><p>我们知道，对于 NSString 的操作需要使用 copy ，以保证我们对它操作时是安全及不可变的。这里针对 message、file、function 却不采用 copy，是为了避免不必要的 allocations 开销。因为 file 和 function 是通过 __FILE__ and __FUNCTION__ 这两个宏来获取的，它们本质上就是一个字符常量，所以可以这么操作。而 message 正常由 DDlog 内部生成的，Lumberjack 来保证 mesage 不可修改。So 官方提示如下：</p><blockquote><em>If you find need to manually create logMessage objects, there is one thing you should be aware of.</em></blockquote><p>说的就是，当你需要手动生成 log message 的时候需要注意，这三个参数的内存修饰操作。</p><p>log message 内部实现就比较简单了，以 message 字段为例：</p><pre><strong>BOOL</strong> copyMessage = (options &amp; DDLogMessageDontCopyMessage) == <strong>0</strong>;<br>_message = copyMessage ? [message copy] : message;</pre><p>另外，就是每个 logMessage 会记录当前调用的 thread &amp; queue 信息，分别如下:</p><pre>__uint64_t tid;<br>if (pthread_threadid_np(NULL, &amp;tid) == <strong>0</strong>) {<br>    _threadID = [[NSString alloc] initWithFormat:@&quot;%llu&quot;, tid];<br>} else {<br>    _threadID = @&quot;missing threadId&quot;;<br>}<br>_threadName   = NSThread.currentThread.name;<br><em>// Try to get the current queue&#39;s label<br></em>_queueLabel = [[NSString alloc] initWithFormat:@&quot;%s&quot;, dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)];<br>if (@available(macOS <strong>10.10</strong>, iOS <strong>8.0</strong>, *))<br>    _qos = (NSUInteger) qos_class_self();</pre><h3>DDLogLevel</h3><blockquote><em>Log levels are used to filter out logs. Used together with flags.</em></blockquote><p>每一条 log mesage 都设置了对应的日志级别，用于过滤 logs 的。其定义是一个枚举：</p><pre>typedef NS_ENUM(NSUInteger, DDLogLevel) {<br>    <em>// No logs<br></em>    DDLogLevelOff       = <strong>0</strong>, <br>    <em>// Error logs only<br></em>    DDLogLevelError     = (DDLogFlagError), <br>    <em>// Error and warning logs<br></em>    DDLogLevelWarning   = (DDLogLevelError   | DDLogFlagWarning),<br>    <em>// Error, warning and info logs<br></em>    DDLogLevelInfo      = (DDLogLevelWarning | DDLogFlagInfo), <br>    <em>// Error, warning, info and debug logs<br></em>    DDLogLevelDebug     = (DDLogLevelInfo    | DDLogFlagDebug), <br>    <em>// Error, warning, info, debug and verbose logs<br></em>    DDLogLevelVerbose   = (DDLogLevelDebug   | DDLogFlagVerbose), <br>    <em>// All logs (1...11111)<br></em>    DDLogLevelAll       = NSUIntegerMax <br>};</pre><p>而 loglevel 是由 DDLogFlag 控制，其声明如下：</p><pre>typedef NS_OPTIONS(NSUInteger, DDLogFlag) {<br>    <em>// 0...00001 DDLogFlagError<br></em>    DDLogFlagError      = (<strong>1</strong> &lt;&lt; <strong>0</strong>),<br>    <em>// 0...00010 DDLogFlagWarning<br></em>    DDLogFlagWarning    = (<strong>1</strong> &lt;&lt; <strong>1</strong>),<br>    <em>// 0...00100 DDLogFlagInfo<br></em>    DDLogFlagInfo       = (<strong>1</strong> &lt;&lt; <strong>2</strong>),<br>    <em>// 0...01000 DDLogFlagDebug<br></em>    DDLogFlagDebug      = (<strong>1</strong> &lt;&lt; <strong>3</strong>),<br>    <em>// 0...10000 DDLogFlagVerbose<br></em>    DDLogFlagVerbose    = (<strong>1</strong> &lt;&lt; <strong>4</strong>)<br>};</pre><p>这些就是 DDLog 所预设的 5 种 level，对于新手来说基本够用了。同时，对于有自定义 level 需求的用户来说，可以通过结构化的宏，就能轻松实现。详见 <a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomLogLevels.md">CustomLogLevels.md</a> 。</p><p>其核心是先将预设的 level 清除，然后在进行重新定义：</p><pre><em>// First undefine the default stuff we don&#39;t want to use.<br>#undef DDLogError<br>#undef DDLogWarn<br>#undef DDLogInfo<br>#undef DDLogDebug<br>#undef DDLogVerbose<br></em>...<br><em>// Now define everything how we want it<br>#define LOG_FLAG_FATAL   (1 &lt;&lt; 0)  // 0...000001<br>#define LOG_LEVEL_FATAL   (LOG_FLAG_FATAL)  // 0...000001<br>#define LOG_FATAL   (ddLogLevel &amp; LOG_FLAG_FATAL )<br>#define DDLogFatal(frmt, ...)    SYNC_LOG_OBJC_MAYBE(ddLogLevel, LOG_FLAG_FATAL,  0, frmt, ##__VA_ARGS__)<br></em>...</pre><p>除了对 level 的重定义之外，我们也可以通过对 level 进行扩展来满足我们对需求。由于 lumberjack 使用的是 bitmask 且只预设了 5 个 bit，对应 5 种 log flag。</p><p>而 logLevel 作为 Int 类型，意味着对于 32 位的系统而言，预留给我们的 levels 还有 28 bits，因为默认的 level 仅仅占用了 4 bits。扩展空间可以说是绰绰有余的。官方提供了两个需要进行扩展的场景，详见： <a href="https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/FineGrainedLogging.md">FineGrainedLogging.md</a> 。</p><h3>DDLoger</h3><blockquote><em>This protocol describes a basic logger behavior.</em></blockquote><blockquote>- Basically, it can log messages, store a logFormatter plus a bunch of optional behaviors.</blockquote><blockquote>- (i.e. flush, get its loggerQueue, get its name, …</blockquote><pre>@protocol DDLogger &lt;NSObject&gt;<br><br>- (<strong>void</strong>)logMessage:(DDLogMessage *)logMessage NS_SWIFT_NAME(log(message:));<br>@property (nonatomic, strong, nullable) <strong>id</strong> &lt;DDLogFormatter&gt; logFormatter;<br><br>@optional<br>- (<strong>void</strong>)didAddLogger;<br>- (<strong>void</strong>)didAddLoggerInQueue:(dispatch_queue_t)queue;<br>- (<strong>void</strong>)willRemoveLogger;<br>- (<strong>void</strong>)flush;<br><br>@property (nonatomic, DISPATCH_QUEUE_REFERENCE_TYPE, readonly) dispatch_queue_t loggerQueue;<br>@property (copy, nonatomic, readonly) DDLoggerName loggerName;<br><br>@end</pre><p>logMessage 没啥好说的，logFormatter 会在后面介绍。重点看上面的几个 optional 方法和参数。</p><p><strong>loggerQueue</strong></p><p>先看 loggerQueue，由于日志打印均为异步操作，所以会为每个 looger 分配一个 dispatch_queue_t。如果 logger 未提供 loggerQueue，那么 DDLog 为根据你所指定的 loggerName 主动为你生成。</p><p><strong>didAddLogger</strong></p><p>同样由于异步打印日志的原因，looger 被添加到 loogers 中时也是异步的过程，didAddLogger 方法就是用于通知 logger 已被成功添加，而这个操作时在 loggerQueue 中完成的。</p><p>同样， didAddLoggerInQueue: 和 willRemoveLogger 目的也是类似。</p><p><strong>flush</strong></p><p>用于刷新存在在队列中还未处理的 log message。比如，database logger 可能通过 I/O buffer 来减少日志存储频率，毕竟磁盘 I/O 是比较耗时的，这种情况下，logger 中可能留有未被及时处理的 log message。</p><p>DDLog 会通过 flushLog 来执行 flush 。需要⚠️的是，当应用退出的时候 flushLog 会被自动调用。当然，作为开发者我们可以在适当的情况下手动触发刷新，正常是不需要手动触发的。</p><h3>DDLogFormatter</h3><blockquote><em>Formatter allow you to format a log message before the logger logs it.</em></blockquote><pre>@protocol DDLogFormatter &lt;NSObject&gt;<br><br>@required<br>- (nullable NSString *)formatLogMessage:(DDLogMessage *)logMessage NS_SWIFT_NAME(format(message:));<br><br>@optional<br>- (<strong>void</strong>)didAddToLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger;<br>- (<strong>void</strong>)didAddToLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger inQueue:(dispatch_queue_t)queue;<br>- (<strong>void</strong>)willRemoveFromLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger;<br><br>@end</pre><p><strong>formatLogMessage:</strong></p><p>formatter 是可以添加到任何 logger 上的，通过 formatLogMessage: 极大提高了 logging 的自由度。怎么理解呢？我们可以通过 formatLogMessage: 给 file logger 和 console 返回不同的结果。例如 console 一般系统会自动在 log 前添加时间戳，而当我们写入 log file 时就需要自行来添加时间。我们还可以通过返回 nil 将其作为 filter 来过滤对应的 log。</p><p><strong>didAddToLogger</strong></p><p>一个 formatter 可以被添加到多个 logger 上。当 formatter 被添加时，通过这个方法来通知它。该方法是需要保证线程安全的，否则可能会出现线程安全异常。</p><p>同理， didAddToLogger: inQueue 是指在指定队列中进行 format 操作。</p><p>willRemoveFromLogger 则是 formatter 被移除时的通知。</p><h3>DDLog</h3><blockquote><em>The main class, exposes all logging mechanisms, loggers, …</em></blockquote><blockquote><em>For most of the users, this class is hidden behind the logging functions like </em><em>DDLogInfo</em></blockquote><p>DDLog 作为 lumberjack 的管理类，负责将用户的 log 信息收集后集中调度至不同的 logger 已达到不同的功能，比如 console log 和 file log。因此，作为单例是必须的。我们先来看看它初始化都准备了什么东西。</p><h4>Initialize</h4><p>上面几个均为私有变量，_loggers 自不必说，任何 logger 的添加/删除都需要在 loggingQueue/loggingThread 中进行的。</p><p><strong>_loggingQueue</strong></p><p>全局的 log queue 用于保证 FIFO 的操作顺序，所有 logger 会通过它来顺序执行各 logger 的 logMessage: 。</p><p><strong>_loggingGroup</strong></p><p>由于每个 logger 添加时候都配置了对应的 log queue。因此，loggers 之间的记录行为是并发执行的。而 dispatch group 可以同步所有 loggers 的操作，确保记录行为顺利完成。</p><p><strong>_queueSemaphore</strong></p><p>防止所使用的队列过爆。由于大多数记录都是异步操作，因此，可能遭到恶意线程大量的增加 log 影响正常的记录行为。最大限制数为 DDLOG_MAX_QUEUE_SIZE (1000)，也就是说当队列数超过限制，则会主动阻塞线程，以待执行队列降至安全水平。</p><p>例如：在大型循环中随意添加日志语句时会发生过💥。</p><p><strong>_numProcessors</strong></p><p>记录处理器内核数量，以针对单核情况时进行相应的优化。</p><p>作为静态变量，其初始化则放在 initialize ，如下：</p><pre>+ (<strong>void</strong>)initialize {<br>    static dispatch_once_t DDLogOnceToken;<br><br>    dispatch_once(&amp;DDLogOnceToken, ^{<br>        NSLogDebug(@&quot;DDLog: Using grand central dispatch&quot;);<br><br>        _loggingQueue = dispatch_queue_create(&quot;cocoa.lumberjack&quot;, NULL);<br>        _loggingGroup = dispatch_group_create();<br><br>        <strong>void</strong> *nonNullValue = GlobalLoggingQueueIdentityKey; <em>// Whatever, just not null<br></em>        dispatch_queue_set_specific(_loggingQueue, GlobalLoggingQueueIdentityKey, nonNullValue, NULL);<br><br>        _queueSemaphore = dispatch_semaphore_create(DDLOG_MAX_QUEUE_SIZE);<br><br>        <em>// Figure out how many processors are available.<br></em>        <em>// This may be used later for an optimization on uniprocessor machines.<br></em><br>        _numProcessors = MAX([NSProcessInfo processInfo].processorCount, (NSUInteger) <strong>1</strong>);<br><br>        NSLogDebug(@&quot;DDLog: numProcessors = %@&quot;, @(_numProcessors));<br>    });<br>}</pre><p>上述代码中，通过 dispatch_queue_set_specific 为 _loggingQueue 添加了 key： <strong>GlobalLoggingQueueIdentityKey</strong> 作为标记。之后会在所有的内部方法执行前通过 dispatch_get_specific 获取 flag 来进行断言，确保内部方法都是在全局的 _loggingQueue 中调度的。</p><p>接着，我们来看看 DDLog 实例的初始化，仅做了两件事：</p><ul><li>_loggers 初始化；</li><li>尝试注册通知，确保 APP 进程结束前能够及时将 Logger 中的 message 处理完毕；</li></ul><p>由于 lumberjack 支持全平台以及命令行，这里的 notificationName 判断条件相对多一些：</p><pre><em>#if TARGET_OS_IOS<br></em>    NSString *notificationName = UIApplicationWillTerminateNotification;<br><em>#else<br></em>    NSString *notificationName = nil;<br>    <em>// On Command Line Tool apps AppKit may not be available<br>#if !defined(DD_CLI) &amp;&amp; __has_include(&lt;AppKit/NSApplication.h&gt;)<br></em>    if (NSApp) {<br>        notificationName = NSApplicationWillTerminateNotification;<br>    }<br><em>#endif<br></em>    if (!notificationName) {<br>        <em>// If there is no NSApp -&gt; we are running Command Line Tool app.<br></em>        <em>// In this case terminate notification wouldn&#39;t be fired, so we use workaround.<br></em>        __weak __auto_type weakSelf = self;<br>        atexit_b (^{<br>            [weakSelf applicationWillTerminate:nil];<br>        });<br>    }<br><em>#endif /* if TARGET_OS_IOS */</em></pre><p>稍微提一点，命令行中是如何来监听程序退出？这里用到了 atexit</p><blockquote><em>The atexit() function registers the given function to be called at program exit, whether via exit(3) or via return from the program’s main(). Functions so registered are called in reverse order; no arguments are passed.</em></blockquote><p>就是说，程序在退出时，系统会主动调用通过 atexit 注册的 callbacks，可以注册多个回调，按照顺序执行。</p><p>DDLog 在收到通知后会触发 flush ，这个我们晚一点展开。</p><pre>if (notificationName) {<br>    [[NSNotificationCenter defaultCenter] addObserver:self<br>                                             selector:@selector(applicationWillTerminate:)<br>                                                 name:notificationName<br>                                               object:nil];<br>}<br><br>- (<strong>void</strong>)applicationWillTerminate:(NSNotification * __attribute__((unused)))notification {<br>    [self flushLog];<br>}</pre><h3>Logger Management</h3><p>对 logger 的操作主要是添加和删除。</p><p><strong>AddLogger</strong></p><p>DDLog 提供了多个添加 logger 的 convince 方法：</p><pre>+ (<strong>void</strong>)addLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger;<br>- (<strong>void</strong>)addLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger;<br>+ (<strong>void</strong>)addLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger withLevel:(DDLogLevel)level;<br>- (<strong>void</strong>)addLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger withLevel:(DDLogLevel)level；<br><br>- (<strong>void</strong>)addLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger withLevel:(DDLogLevel)level {<br>    if (!logger) {<br>        return;<br>    }<br>    dispatch_async(_loggingQueue, ^{ @autoreleasepool {<br>        [self lt_addLogger:logger level:level];<br>    } });<br>}</pre><p>在放入 _loggingQueue 后，最终走到了 lt_addLogger: level: 方法。这里的前缀 lt 是 lgging thread 的缩写。在 logger 添加前会检查去重：</p><pre>for (DDLoggerNode *node in self._loggers) {<br>    if (node-&gt;_logger == logger &amp;&amp; node-&gt;_level == level) {<br>        <em>// Exactly same logger already added, exit<br></em>        return;<br>    }<br>}</pre><p><strong>DDLoggerNode</strong></p><pre>@interface DDLoggerNode : NSObject<br>{<br>    <em>// Direct accessors to be used only for performance<br></em>    @public<br>    <strong>id</strong> &lt;DDLogger&gt; _logger;<br>    DDLogLevel _level;<br>    dispatch_queue_t _loggerQueue;<br>}<br><br>+ (<strong>instancetype</strong>)nodeWithLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger<br>                   loggerQueue:(dispatch_queue_t)loggerQueue<br>                         level:(DDLogLevel)level;</pre><p>私有类，用于关联 logger、level 和 loggerQueue。</p><p>稍微提一下，在 DDLoggerNode 的初始化方法中的，兼容了 MRC 的使用。内部使用了一个宏 OS_OBJECT_USE_OBJC 来区分 GCD 是否支持 ARC。在6.0 之前 GCD 中的对象是不支持 ARC，因此在 6.0 之前 OS_OBJECT_USE_OBJC 是没有的。</p><pre>if (loggerQueue) {<br>    _loggerQueue = loggerQueue;<br>    <em>#if !OS_OBJECT_USE_OBJC<br></em>    dispatch_retain(loggerQueue);<br>    <em>#endif<br></em>}</pre><p>接着就是前面所提到的 QueueIdentity 的断言：</p><pre>NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),<br>         @&quot;This method should only be run on the logging thread/queue&quot;);</pre><p>准备 loggerQueue：</p><pre>dispatch_queue_t loggerQueue = NULL;<br>if ([logger respondsToSelector:@selector(loggerQueue)]) {<br>    loggerQueue = logger.loggerQueue;<br>}<br><br>if (loggerQueue == nil) {<br>    const <strong>char</strong> *loggerQueueName = NULL;<br>    if ([logger respondsToSelector:@selector(loggerName)]) {<br>        loggerQueueName = logger.loggerName.UTF8String;<br>    }<br>    loggerQueue = dispatch_queue_create(loggerQueueName, NULL);<br>}</pre><p>这段代码，有没有似曾相识的干？这是在 DDLogger Protocol 声明时提到的逻辑。如果 logger 提供了 loggerQueue 则直接使用。否则，通过 loggerName 来创建。</p><p>最后就是创建 DDLoggerNode，添加 logger，发送 didAddLogger 通知。</p><pre>DDLoggerNode *loggerNode = [DDLoggerNode nodeWithLogger:logger loggerQueue:loggerQueue level:level];<br>[self._loggers addObject:loggerNode];<br><br>if ([logger respondsToSelector:@selector(didAddLoggerInQueue:)]) {<br>    dispatch_async(loggerNode-&gt;_loggerQueue, ^{ @autoreleasepool {<br>        [logger didAddLoggerInQueue:loggerNode-&gt;_loggerQueue];<br>    } });<br>} else if ([logger respondsToSelector:@selector(didAddLogger)]) {<br>    dispatch_async(loggerNode-&gt;_loggerQueue, ^{ @autoreleasepool {<br>        [logger didAddLogger];<br>    } });<br>}</pre><p><strong>RemoveLogger</strong></p><p>同 addLogger 类似，removeLogger 也提供了实例方法和类方法。类方法通过 sharedInstance 最终收口到实例方法：</p><pre>- (<strong>void</strong>)removeLogger:(<strong>id</strong> &lt;DDLogger&gt;)logger {<br>    if (!logger) {<br>        return;<br>    }<br>    dispatch_async(_loggingQueue, ^{ @autoreleasepool {<br>        [self lt_removeLogger:logger];<br>    } });<br>}</pre><p><strong>-[DDLog lt_removeLogger:]</strong></p><p>删除前，照例是 loggingQueue 检查，然后遍历获取 loggerNode：</p><pre>DDLoggerNode *loggerNode = nil;<br>for (DDLoggerNode *node in self._loggers) {<br>    if (node-&gt;_logger == logger) {<br>        loggerNode = node;<br>        break;<br>    }<br>}</pre><p>如果 loggerNode 不存在，则提前结束。存在，则会先向 loggerNode 发送 willRemoveLogger 通知，再移除。</p><pre>if ([logger respondsToSelector:@selector(willRemoveLogger)]) {<br>    dispatch_async(loggerNode-&gt;_loggerQueue, ^{ @autoreleasepool {<br>        [logger willRemoveLogger];<br>    } });<br>}<br>[self._loggers removeObject:loggerNode];</pre><p>DDLog 还提供了 removeAllLoggers 的方法，以一次性清零 loggers，实现同 lt_removeLogger: 类似，这里不展开了。</p><h3>Logging</h3><p>logging 相关方法是 DDLog 的核心，提供三种类型的实例方法，以及分别对应的类方法。我们来看第一个：</p><pre>+ (<strong>void</strong>)log:(<strong>BOOL</strong>)asynchronous<br>      level:(DDLogLevel)level<br>       flag:(DDLogFlag)flag<br>    context:(NSInteger)context<br>       file:(const <strong>char</strong> *)file<br>   function:(nullable const <strong>char</strong> *)function<br>       line:(NSUInteger)line<br>        tag:(nullable <strong>id</strong>)tag<br>     format:(NSString *)format, ... NS_FORMAT_FUNCTION(<strong>9</strong>,<strong>10</strong>);</pre><p>熟悉吧，这些参数前面都介绍过了，是构造 log message 所需的关参数。最后一个 C 写法的可变参数 ... 用于生成 log message string，同样 DDLog 也提供了它的变种 args:(va_list)argList ，这就是第二种 log 方法。最后一种则是由用户直接提供 logMessage。</p><p>对于 ... 的可变参数的获取，是通过 c 提供的宏，代码如下：</p><pre>va_list args;<br>va_start(args, format);<br>NSString *message = [[NSString alloc] initWithFormat:format arguments:args];<br>va_end(args);</pre><p><strong>-[DDLog queueLogMessage: asynchronously:]</strong></p><p>准备好 log message 则开始分发，进行异步调用：</p><pre>- (<strong>void</strong>)queueLogMessage:(DDLogMessage *)logMessage asynchronously:(<strong>BOOL</strong>)asyncFlag {<br>   dispatch_block_t logBlock = ^{<br>        dispatch_semaphore_wait(_queueSemaphore, DISPATCH_TIME_FOREVER);<br>        @autoreleasepool {<br>            [self lt_log:logMessage];<br>        }<br>    };<br><br>    if (asyncFlag) {<br>        dispatch_async(_loggingQueue, logBlock);<br>    } else if (dispatch_get_specific(GlobalLoggingQueueIdentityKey)) {<br>        logBlock();<br>    } else {<br>        dispatch_sync(_loggingQueue, logBlock);<br>    }<br>}</pre><p>先忽略 logBlock，看 DDLog 如果处理 loggingQueue 调度，以及如何来避免线程死锁问题。这里的解决方式绝对需要 <strong>划重点</strong> 。大家经常遇到的主线程死锁，很常见的情况如下：</p><pre>- (<strong>void</strong>)viewDidLoad {<br>    [super viewDidLoad];<br>    NSLog(@&quot;1&quot;);<br>    dispatch_sync(dispatch_get_main_queue(), ^{<br>        NSLog(@&quot;2&quot;);<br>    });<br>    NSLog(@&quot;3&quot;);<br>}</pre><p>这个也是面试会被常常问到的 case。核心点在于，上述代码在 main thread 执行了 dispatch_sync 开启了 main queue 的同步等待。解决方案就有很多种，比如 SDWebImage 中就提供了 <a href="https://looseyi.github.io/post/sourcecode-ios/source-code-sdweb-1/">dispatch_main_async_safe</a> 来避免该问题。</p><p>回到 DDLog，现在大家可以明白在 dispatch_sync 前为何需要多一步 queue identity 的判断了吧。另外，关于这个问题， <a href="https://github.com/CocoaLumberjack/CocoaLumberjack/issues/812#issuecomment-298853313">github issuse #812</a> 中有比较详细的论述。</p><p>接着看 logBlock，它在执行第一行代码时，就开启了 semaphore_wait 直到可用队列数小于 maximumQueueSize。通常来说，我们会通过给 queueSize 加锁的方式来确保可用队列数的准确性和线程安全。但是这里作者希望，能够更快速的来获取添加 log mesage 入队列的时机，毕竟锁的开销比较大。</p><p>这种实践在很多优秀开源库中都用到了，比如 SDWebImage。</p><p><strong>- [DDLog lt_log:]</strong></p><p>该方法是将 log message 分配到所以满足的 logger 手中。开始前照例进行 QueueIdentity 的断言。接着依据 CPU 内核数是单核或者多核区别对待：</p><pre>if (_numProcessors &gt; <strong>1</strong>) {  ... } else { ... }</pre><ol><li>多核处理器，代码如下：</li></ol><pre>for (DDLoggerNode *loggerNode in self._loggers) {<br>    if (!(logMessage-&gt;_flag &amp; loggerNode-&gt;_level)) {<br>        continue;<br>    }<br>    dispatch_group_async(_loggingGroup, loggerNode-&gt;_loggerQueue, ^{ @autoreleasepool {<br>        [loggerNode-&gt;_logger logMessage:logMessage];<br>    } });<br>}<br>dispatch_group_wait(_loggingGroup, DISPATCH_TIME_FOREVER);1</pre><p>稍微提一下 DDLog 的设计思路，由于一条 log message 可能会提供给多个不同类型的 logger 处理。例如，一条 log 可能同时需要输出到终端、写入到 log file 中、通过 websocket 输出到浏览器方便测试等操作。</p><p>首先，通过 logMessage-&gt;_flag 过滤掉 level 不匹配的 loggerNode。然后从匹配到的 loggerNode 中取出 loggerQueue 和 logger 调用 logMessage: 。</p><p>重点来了，这里利用 _loggingGroup 将本次的 logMessage: 关联到 group 中，打包成一个 &quot;事务&quot;，以保证每次的 lt_log: 都是顺序执行的。而每个 logger 本身都分配了独立的 loggerQueue，通过这种组合，即保证了 logger 的并发调用，又能满足 queueSize 的限制。</p><p>使用 dispatch_group_wait 还有一个目的，就是确保那些执行效果慢的 logger 也能按顺序完成调用，避免队列任务过多时，这些 logger 没能及时完成导致大量的 padding log message 没有被及时处理。</p><p>2. 对单核处理就比较简单了，就是第二步不同。不存在 gropu 操作：</p><pre>dispatch_sync(loggerNode-&gt;_loggerQueue, ^{ @autoreleasepool {<br>    [loggerNode-&gt;_logger logMessage:logMessage];<br>} });</pre><p>最后，分配完 logger message 后，需要将 _queueSemaphore 加 1:</p><pre>dispatch_semaphore_signal(_queueSemaphore);</pre><p><strong>lt_flush</strong></p><p>DDLog 的最后一个方法，会在程序结束前由通知来触发执行，其实现同 lt_log: 类似：</p><pre>- (<strong>void</strong>)lt_flush {<br>    NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),<br>             @&quot;This method should only be run on the logging thread/queue&quot;);<br><br>    for (DDLoggerNode *loggerNode in self._loggers) {<br>        if ([loggerNode-&gt;_logger respondsToSelector:@selector(flush)]) {<br>            dispatch_group_async(_loggingGroup, loggerNode-&gt;_loggerQueue, ^{ @autoreleasepool {<br>                [loggerNode-&gt;_logger flush];<br>            } });<br>        }<br>    }<br>    dispatch_group_wait(_loggingGroup, DISPATCH_TIME_FOREVER);<br>}</pre><h3>小结</h3><p>DDLog 名副其实的 manager，利用了信号量和 group 高效的完成对 message 的调度，主要做了以下工作：</p><ol><li>管理 logger 的生命周期，并对其添加、删除操作进行相应通知；</li><li>生成 logMessage 并在线程安全的情况下，将其分配到对应的 logger 以加工 message。</li><li>在程序结束后，及时通知 logger 清理 pending 状态的 message。</li></ol><p>现在我们来聊聊 logger。DDLog 给我们提供了一个 logger 基类 DDAbstractLogger 以及几个默认实现。一一来过一下；</p><h3>DDAbstractLogger</h3><p>AbstractLogger 声明如下：</p><pre>@interface DDAbstractLogger : NSObject &lt;DDLogger&gt;<br>{<br>    @public<br>    <strong>id</strong> &lt;DDLogFormatter&gt; _logFormatter;<br>    dispatch_queue_t _loggerQueue;<br>}<br><br>@property (nonatomic, strong, nullable) <strong>id</strong> &lt;DDLogFormatter&gt; logFormatter;<br>@property (nonatomic, DISPATCH_QUEUE_REFERENCE_TYPE) dispatch_queue_t loggerQueue;<br>@property (nonatomic, readonly, getter=isOnGlobalLoggingQueue)  <strong>BOOL</strong> onGlobalLoggingQueue;<br>@property (nonatomic, readonly, getter=isOnInternalLoggerQueue) <strong>BOOL</strong> onInternalLoggerQueue;<br><br>@end</pre><p>先看初始化方法 init ：</p><h3>Init</h3><p>AdstractLogger 默认提供了 loggerQueue 以及当前是否为 loggerQueue 和 全局 loggingQueue 的 convene 方法。loggerQueue 的初始化是在 init 中完成的，整个 init 也就做了这一件事。</p><pre>const <strong>char</strong> *loggerQueueName = NULL;<br><br>if ([self respondsToSelector:@selector(loggerName)]) {<br>    loggerQueueName = self.loggerName.UTF8String;<br>}<br><br>_loggerQueue = dispatch_queue_create(loggerQueueName, NULL);<br><strong>void</strong> *key = (__bridge <strong>void</strong> *)self;<br><strong>void</strong> *nonNullValue = (__bridge <strong>void</strong> *)self;<br>dispatch_queue_set_specific(_loggerQueue, key, nonNullValue, NULL);</pre><p>同样先获取 queueName，这里默认返回的 loggerName 是 NSStringFromClass([self class]); 。</p><p>同时，以 self 的地址作为 flag 关联到 loggerQueue，并用于判断 onInternalLoggerQueue 。</p><h3>LogFormatter</h3><p>AdstractLogger 最主要的是实现了 logFormatter 的 getter/setter 方法。同时代码中赋予了十分详细的说明，先看看 getter 实现。</p><p><strong>Getter</strong></p><p>首先是线程相关的断言，确保当前不在 global queue 和 loggerQueue：</p><pre>NSAssert(![self isOnGlobalLoggingQueue], @&quot;Core architecture requirement failure&quot;); NSAssert(![self isOnInternalLoggerQueue], @&quot;MUST access ivar directly, NOT via self.* syntax.&quot;);</pre><p>接着在 loggingQueue 和 loggerQueue 中获取 logFormatter：</p><pre>dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];<br><br>__block <strong>id</strong> &lt;DDLogFormatter&gt; result;<br><br>dispatch_sync(globalLoggingQueue, ^{<br>    dispatch_sync(self-&gt;_loggerQueue, ^{<br>        result = self-&gt;_logFormatter;<br>    });<br>});<br>return result;</pre><p>看去一个普通的 formatter 为何需要如此大动干戈，需要层层深入来呢？我们来看一段代码：</p><pre>DDLogVerbose(@&quot;log msg 1&quot;);<br>DDLogVerbose(@&quot;log msg 2&quot;);<br>[logger setFormatter:myFormatter];<br>DDLogVerbose(@&quot;log msg 3&quot;);</pre><p>从直觉上，我们希望看到的结果是新设置的 formatter 仅应用在第 3 条 log message 上。然而 DDLog 在整个 logging 过程中却都是异步调用的。</p><ol><li>log message 最终是在单独的 loggerQueue 中执行的，是由 logger 各自持有的 queue；</li><li>在进入每个 loggerQueue 之前，又要经过一道全局的 loggingQueue。</li></ol><p>So，想要线程安全又要符合直觉的话，只能遵循 log message 的脚步，走一遍相关 queue。</p><p>需要强调一点，logger在内部 <strong>最好直接访问 FORMATTER VARIABLE</strong> ，如果需要的话。一旦使用 self. 可能会导致线程死锁。</p><p><strong>Setter</strong></p><p>同 getter 一致，先断言，然后依次进入队列 DDLog.loggingQueue -&gt; self-&gt;_loggerQueue 执行 block 开始真正的赋值：</p><pre>@autoreleasepool {<br>    if (self-&gt;_logFormatter != logFormatter) {<br>        if ([self-&gt;_logFormatter respondsToSelector:@selector(willRemoveFromLogger:)]) {<br>            [self-&gt;_logFormatter willRemoveFromLogger:self];<br>        }<br><br>        self-&gt;_logFormatter = logFormatter;<br><br>        if ([self-&gt;_logFormatter respondsToSelector:@selector(didAddToLogger:inQueue:)]) {<br>            [self-&gt;_logFormatter didAddToLogger:self inQueue:self-&gt;_loggerQueue];<br>        } else if ([self-&gt;_logFormatter respondsToSelector:@selector(didAddToLogger:)]) {<br>            [self-&gt;_logFormatter didAddToLogger:self];<br>        }<br>    }<br>}</pre><h3>DDASLLogger</h3><p>ASLLogger 是对 <strong>Apple System Log</strong> API 的封装，我们经常使用的 NSLog 会将其输出定向到两个地方：</p><ul><li><a href="https://support.apple.com/zh-cn/guide/console/cnsl1012/mac">Apple System Log</a></li><li><a href="https://www.wikiwand.com/en/Standard_streams">Standard error</a>（telemetry）</li></ul><p>不过 ASLLogger 在 macosx 10.12 iOS 10.0 已经被废弃了，取而代之的是 DDOSLoger。ASLLogger 背后使用的 API 是 <a href="https://opensource.apple.com/source/Libc/Libc-583/include/asl.h.auto.html"><strong>&lt;asl.h&gt;</strong></a> ，它也提供了几种 message level</p><pre><em>/*! @defineblock Log Message Priority Levels Log levels of the message. */</em><br><em>#define ASL_LEVEL_EMERG   0<br>#define ASL_LEVEL_ALERT   1<br>#define ASL_LEVEL_CRIT    2 // DDLogFlagError<br>#define ASL_LEVEL_ERR     3 // DDLogFlagWarning<br>#define ASL_LEVEL_WARNING 4 // DDLogFlagInfo, Regular NSLog&#39;s level<br>#define ASL_LEVEL_NOTICE  5 // default<br>#define ASL_LEVEL_INFO    6<br>#define ASL_LEVEL_DEBUG   7</em></pre><p>默认情况下 ASL 会过滤 NOTICE 之上的信息，这也是为何 DDLog 基本也就设置了 5 种日志级别。</p><h3>logMessage</h3><p>logMessage 是每个 logger 处理 log message 的方法。ASLLogger 首先会过滤 filename 为 DDASLLogCapture (主动监听的系统 log)。然后对 message 进行 formate：</p><pre>NSString * message = _logFormatter ? [_logFormatter formatLogMessage:logMessage] : logMessage-&gt;_message;</pre><p>如果 message 存在，生成 aslmsg 通过 asl_send 发送至 ASL。实现如下：</p><pre>const <strong>char</strong> *msg = [message UTF8String];<br>size_t aslLogLevel; <em>// logMessage-&gt;_flag 获取 ASL_LEVEL_XXX<br></em><br>static <strong>char</strong> const *const level_strings[] = { &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot; };<br><br>uid_t const readUID = geteuid(); <em>/// the effective user ID of the calling process<br></em><br><strong>char</strong> readUIDString[<strong>16</strong>]; <em>/// formatted output conversion<br>#ifndef NS_BLOCK_ASSERTIONS<br></em>size_t l = (size_t)snprintf(readUIDString, sizeof(readUIDString), &quot;%d&quot;, readUID);<br><em>#else<br></em>snprintf(readUIDString, sizeof(readUIDString), &quot;%d&quot;, readUID);<br><em>#endif<br></em><br>NSAssert(l &lt; sizeof(readUIDString), @&quot;Formatted euid is too long.&quot;);<br>NSAssert(aslLogLevel &lt; (sizeof(level_strings) / sizeof(level_strings[<strong>0</strong>])), @&quot;Unhandled ASL log level.&quot;);<br><br>aslmsg m = asl_new(ASL_TYPE_MSG);<br>if (m != NULL) {<br>    if (asl_set(m, ASL_KEY_LEVEL, level_strings[aslLogLevel]) == <strong>0</strong> &amp;&amp;<br>        asl_set(m, ASL_KEY_MSG, msg) == <strong>0</strong> &amp;&amp;<br>        asl_set(m, ASL_KEY_READ_UID, readUIDString) == <strong>0</strong> &amp;&amp;<br>        asl_set(m, kDDASLKeyDDLog, kDDASLDDLogValue) == <strong>0</strong>) {<br>        asl_send(_client, m);<br>    }<br>    asl_free(m);<br>}</pre><h3>DDOSLogger</h3><p>苹果的新一代 logging system <a href="https://developer.apple.com/documentation/os/logging">os_log</a> ，官方提供了比较完整的概述和说明。正是它取代了 ASL，manual 如下：</p><blockquote><em>The unified logging system provides a single, efficient, high performance set of APIs for capturing log messages across all levels of the system. This unified system centralizes the storage of log data in memory and in a data store on disk.</em></blockquote><p>它提供了日志记录的中心化存储。同时 API 也十分简洁，关于 os_log 有机会在展开。</p><h3>Init</h3><p>首先，OSLogger 需要持有一个 log object：</p><pre>os_log_t os_log_create(const <strong>char</strong> *subsystem, const <strong>char</strong> *category);</pre><p><strong>subsystem</strong></p><blockquote><em>An identifier string, in reverse DNS notation, that represents the subsystem that’s performing logging, for example, </em><em>com.your_company.your_subsystem_name. The subsystem is used for categorization and filtering of related log messages, as well as for grouping related logging settings.</em></blockquote><p><strong>category</strong></p><blockquote><em>A category within the specified subsystem. The system uses the category to categorize and filter related log messages, as well as to group related logging settings within the subsystem’s settings. A category’s logging settings override those of the parent subsystem.</em></blockquote><p>顺便说一下，os_log 的官方文档是只提供了 Swift 说明，OSLog.Category <a href="https://developer.apple.com/documentation/os/oslog/category">详细点此</a> 。</p><p><strong>LogMessage</strong></p><p>同样是过滤 filename 为 DDASLLogCapture 的 log message 和对 log message 的 formatter。os_log 所提供的 API 则十分友好简洁，每种 <a href="https://developer.apple.com/documentation/kernel/os_log_type_t?language=objc">os_log_type_t</a> 都提供了对应的方法，使用如下：</p><pre>__auto_type logger = [self logger];<br>switch (logMessage-&gt;_flag) {<br>    case DDLogFlagError  :<br>        os_log_error(logger, &quot;%{public}s&quot;, msg);<br>        break;<br>    case DDLogFlagWarning:<br>    case DDLogFlagInfo   :<br>        os_log_info(logger, &quot;%{public}s&quot;, msg);<br>        break;<br>    case DDLogFlagDebug  :<br>    case DDLogFlagVerbose:<br>    default              :<br>        os_log_debug(logger, &quot;%{public}s&quot;, msg);<br>        break;<br>}</pre><h3>DDTTYLogger</h3><blockquote><em>This class provides a logger for Terminal output or Xcode console output, depending on where you are running your code.</em></blockquote><p>通过它将日志定向到终端和 Xcode 终端，同时支持彩色。Xcode 支持需要添加 <a href="https://github.com/robbiehanson/XcodeColors">XcodeColors 插件</a> 。TTYLogger 内部的代码有上千行。不过所做的事情比较简单。根据不同终端类型所支持的颜色范围来将设置的颜色进行适配，最终输出出来。</p><p>关于颜色范围主要有三种类型：</p><ul><li>standard shell：仅支持 16 种颜色</li><li>Terminal.app：可以支持到 256 种颜色</li><li>xterm colors</li></ul><p>具体见 <a href="http://en.wikipedia.org/wiki/ANSI_escape_code">ANSI_escape_code</a> 。</p><h4><strong>LogMessage</strong></h4><p>TTYLogger 支持为每一种 logFlag 配置不同的颜色，然后将 color 与 flag 封装进 DDTTYLoggerColorProfile 类中，存储在 _colorProfilesDict 中。logMessage 主要分三步：</p><ol><li>通过 logMessage-&gt;_tag 取出 colorProfile；</li><li>将 log message 转为 c string；</li><li>将 color 写入 iovec v[iovec_len]，最终调用 writev(STDERR_FILENO, v, iovec_len); 输出。</li></ol><h3>未完待续</h3><p>以上三种 logger 属于基本的终端输出，可用于替代 NSLog。限于篇幅的原因，还有 DDFileLogger、 DDAbstractDatabaseLogger 以及各种扩展，如 WebSocketLogger 等，未在本篇出现。同时还有一整节的 Formatters 均放下一篇中。</p><p>本篇，通过 DDLog 类对 GCD 的使用，看到了 lumberjack 的作者充分利用了 GCD 的特性来达到安全高效的异步 logging。整个过程中并未使用锁来解决线程安全，算是对 GCD 的很好实践了。该作者还出品了 <a href="https://github.com/robbiehanson/CocoaAsyncSocket">CocoaAsyncSocket</a> 、 <a href="https://github.com/robbiehanson/XMPPFramework">XMPPFramework</a>、 <a href="https://github.com/robbiehanson/CocoaHTTPServer">CocoaHTTPServer</a> 等知名的库。之后可以慢慢细品。</p><p>最后，贴一张整理的脑图，比较简单，不喜勿喷。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iUmcpMhuy2bkqLjA.jpg" /></figure><p><em>Originally published at </em><a href="https://looseyi.github.io/post/sourcecode-ios/source-code-lumberjack-1/"><em>https://looseyi.github.io</em></a><em> on May 4, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b7c926e57d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5.6 Code Architecture Analysis]]></title>
            <link>https://medium.com/@liuedmond/5-6-code-architecture-analysis-91b673044c14?source=rss-d3b3aa852ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b673044c14</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[sdwebimage]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[code-analysis]]></category>
            <dc:creator><![CDATA[Liu Edmond]]></dc:creator>
            <pubDate>Tue, 14 Apr 2020 05:25:33 GMT</pubDate>
            <atom:updated>2020-04-14T05:25:33.319Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is based on SDWebImage 5.6. Why i write this article, cause i found that SD’s API is constantly iterating, and many of the structures are different from earlier versions. Here is to make a record. We will start from the top of the API’s level list below, force on the entire framework’s data flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nRtVfQMxb7LVemXb.jpeg" /><figcaption>SDWebImage Architecture 5.x</figcaption></figure><h3>5.0 Migration Guid</h3><p>It is highly recommended to watch the official <a href="https://github.com/SDWebImage/SDWebImage/wiki/5.0-Migration-guide">migration document</a>, which mentioned the mainly features in version 5.0.</p><ul><li>Brand new Animated Image View (was FLAnimatedImageView in 4.0);</li><li>Image Transform is provided to easy way to scale, rotate, rounded corner and other operations after the image was downloaded;</li><li>Customization, you can customize <a href="https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-cache-50">cache</a>, <a href="https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-loader-50">loader</a>, <a href="https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-coder-420">coder</a>, which are base on the protocol;</li><li>Added View Indicator to identify the loading status of Image;</li></ul><p>I could say that the protocolization for the core classes is the biggest change in the 5.x SD version, which means the image request, loading, decoding, caching and other operations are pluggable and replaceable as you want.</p><p>So, let’s see the main part first:</p><p><a href="https://gist.github.com/looseyi/3b1b1fefb2b39df519a46bb5ab3d8188#file-sdwebimage-vdiff-csv">https://gist.github.com/looseyi/3b1b1fefb2b39df519a46bb5ab3d8188</a></p><p>All the view’s convenience method for image operation are base on UIView + WebCache, including the following:</p><ul><li>UIImageView+HighlightedWebCache</li><li>UIImageView+WebCache</li><li>UIView+WebCacheOperation</li><li>UIButton+WebCache</li><li>NSButton+WebCache</li></ul><p>Firstly, let ‘s take a look at <a href="https://github.com/SDWebImage/SDWebImage/blob/09f06159a3284f6981d5495728e5c3cb3dfb82fa/SDWebImage/Core/SDWebImageCompat.h">SDWebImageCompat.h</a> , which defines <strong>SD_MAC, SD_UIKIT, SD_WATCH</strong> macros are used to Simplify the definition of the system, and used to unify the differences platforms API, such as using # define UIImage NSImage to redefine NSImage to UIImage. Another thing you would like to know is:</p><pre>#ifndef dispatch_main_async_safe<br>#define dispatch_main_async_safe(block)\<br>    if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(dispatch_get_main_queue())) {\<br>        block();\<br>    } else {\<br>        dispatch_async(dispatch_get_main_queue(), block);\<br>    }<br>#endif</pre><p>different from the earlier version:</p><pre>#define dispatch_main_async_safe(block)\<br>    if ([NSThread isMainThread]) {\<br>        block();\<br>    } else {\<br>        dispatch_async(dispatch_get_main_queue(), block);\<br>    }<br>#endif</pre><ul><li>use #ifndef to prevent repeated definition of dispatch_main_async_safe;</li><li>Main thread detect change from isMainThread to dispatch_queue_t label</li></ul><p>About the second point, here is a <a href="https://github.com/SDWebImage/SDWebImage/pull/781">Discussion of SD</a>, and another explanation <a href="http://blog.benjamin-encz.de/post/main-queue-vs-main-thread/">GCD’s Main Queue vs. Main Thread</a>)</p><blockquote><em>Calling an API from a non-main queue that is executing on the main thread will lead to issues if the library (like VektorKit) relies on checking for execution on the main queue.</em></blockquote><p>Cause <strong>tasks in the main queue must be put into the main thread to execute</strong>.</p><p>Compared to the category of UIImageView, UIButton needs to store images under different UIControlState and backgroundImage, and SD associate has an internal dictionary (NSMutableDictionary &lt;NSString *, NSURL *&gt; *) sd_imageURLStorage to store the images.</p><p>All view category’s setImageUrl: finally refer to the following method:</p><pre>- (void)sd_internalSetImageWithURL:(nullable NSURL *)url<br>                  placeholderImage:(nullable UIImage *)placeholder<br>                           options:(SDWebImageOptions)options<br>                           context:(nullable SDWebImageContext *)context<br>                     setImageBlock:(nullable SDSetImageBlock)setImageBlock<br>                          progress:(nullable SDImageLoaderProgressBlock)progressBlock<br>                         completed:(nullable SDInternalCompletionBlock)completedBlock;</pre><p>This method’s implementation is quite long, here is the briefly describes:</p><ol><li>Copy and convert SDWebImageContext to immutable, get the value of validOperationKey as the verification id, the default value is the class name of the current view;</li><li>Call sd_cancelImageLoadOperationWithKey to cancel the last task, which to ensure that there is no asynchronous download operation currently in progress and no conflict with the upcoming operation;</li><li>Set the placeholder image;</li><li>Initialize SDWebImageManager , SDImageLoaderProgressBlock , reset NSProgress, SDWebImageIndicator;</li><li>Start downloading, call loadImageWithURL: and save the returned SDWebImageOperation into sd_operationDictionary, which key is validOperationKey;</li><li>After getting the picture, call sd_setImage: and add transition animation to the new image;</li><li>Stop the indicator after the animation ends.</li></ol><p>A tips, the SDWebImageOperation is a <strong>strong-weak</strong> NSMapTable, which is also added by the associated value:</p><pre>// key is strong, value is weak because operation instance is retained by SDWebImageManager&#39;s runningOperations property<br>// we should use lock to keep thread-safe because these method may not be accessed from main queue<br>typedef NSMapTable&lt;NSString *, id&lt;SDWebImageOperation&gt;&gt; SDOperationsDictionary;</pre><p>Weak is used because the operation instance is stored in SDWebImageManager’s runningOperations, and the reference here is saved to easy cancel the task.</p><h3>SDWebImageContext</h3><blockquote><em>A SDWebImageContext object which hold the original context options from top-level API.</em></blockquote><p>Image context runs through the entire workflow of image processing. It brings data into each processing task step by step. There are two types of ImageContext:</p><pre>typedef NSString * SDWebImageContextOption NS_EXTENSIBLE_STRING_ENUM;<br>typedef NSDictionary&lt;SDWebImageContextOption, id&gt; SDWebImageContext;<br>typedef NSMutableDictionary&lt;SDWebImageContextOption, id&gt;SDWebImageMutableContext;</pre><p>SDWebImageContextOption is an extensible String enumeration, there are currently 15 types. Basically, you can guess its function just by looking at the name, here is the <a href="https://github.com/SDWebImage/SDWebImage/blob/5c3c40288f7e465ba94db9736e624f663831951a/SDWebImage/Core/SDWebImageDefine.h">document</a>, summarized as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9zCFVxVDPOxmfUB-" /></figure><p>Prefetcher has nothing to do with the entire processing stream of SD. It mainly uses imageManger for batch image download. Below is the core method:</p><pre>- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray&lt;NSURL *&gt; *)urls<br>                                          progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock<br>                                         completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock;</pre><p>It stores the downloaded URLs as transactions in SDWebImagePrefetchToken, which do not cancel previous request and it separate different prefetching process. When you call prefetchURLs for different url lists, you can get callback for different completion block.</p><p>Each download task is in the autoreleasesepool, and will use SDAsyncBlockOperation to wrap the real download task to achieve the cancelable operation of the task:</p><pre>@autoreleasepool {<br>    @weakify(self);<br>    SDAsyncBlockOperation *prefetchOperation = [SDAsyncBlockOperation blockOperationWithBlock:^(SDAsyncBlockOperation * _Nonnull asyncOperation) {<br>        @strongify(self);<br>        if (!self || asyncOperation.isCancelled) {<br>            return;<br>        }<br>        /// load Image ...<br>    }];<br>    @synchronized (token) {<br>        [token.prefetchOperations addPointer:(__bridge void *)prefetchOperation];<br>    }<br>    [self.prefetchQueue addOperation:prefetchOperation];<br>}</pre><p>Finally, the task is stored in prefetchQueue, which limit the maximum number of downloads to 3 by default. The real task of URLs downloading is in token.loadOperations:</p><pre>NSPointerArray *operations = token.loadOperations;<br>id&lt;SDWebImageOperation&gt; operation = [self.manager loadImageWithURL:url options:self.options context:self.context progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {<br>    /// progress handler    <br>}];<br>NSAssert(operation != nil, @&quot;Operation should not be nil, [SDWebImageManager loadImageWithURL:options:context:progress:completed:] break prefetch logic&quot;);<br>@synchronized (token) {<br>    [operations addPointer:(__bridge void *)operation];<br>}</pre><p>loadOperations and prefetchOperations All use **NSPointerArray **, which uses its NSPointerFunctionsWeakMemory feature and can store Null values, although its performance is not very good, see: <a href="https://objccn.io/issue-7-1/">basic collection Class</a></p><p>Another important thing is that PrefetchToken use the <a href="https://zhuanlan.zhihu.com/p/45566448">c++11 memory_order_relaxed</a> to ensure the thread-safe。</p><pre>atomic_ulong _skippedCount;<br>atomic_ulong _finishedCount;<br>atomic_flag  _isAllFinished;<br>    <br>unsigned long _totalCount;</pre><p>Simply, it use memory order and atomic operations to achieve lock-free concurrency and improving efficiency.</p><p>ImageLoader is the default implementation of the SDImageLoader protocol, which provides HTTP / HTTPS / FTP or local URL NSURLSession source image acquisition capabilities. And it also maximizes the configurability of the entire download process. Main interface as fellow:</p><pre>@interface SDWebImageDownloader : NSObject<br><br>@property (nonatomic, copy, readonly, nonnull) SDWebImageDownloaderConfig *config;<br>@property (nonatomic, strong, nullable) id&lt;SDWebImageDownloaderRequestModifier&gt; requestModifier;<br>@property (nonatomic, strong, nullable) id&lt;SDWebImageDownloaderResponseModifier&gt; responseModifier;<br>@property (nonatomic, strong, nullable) id&lt;SDWebImageDownloaderDecryptor&gt; decryptor;<br>/* ... */<br><br>-(nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url<br>    options:(SDWebImageDownloaderOptions)options<br>    context:(nullable SDWebImageContext *)context<br>   progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock<br>  completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;<br><br>@end</pre><p>the <strong>downloaderConfig</strong> supports the NSCopy protocol, below is the main configurations provided:</p><pre>/// The maximum number of concurrent downloads.<br>@property (nonatomic, assign) NSInteger maxConcurrentDownloads;<br>/// The timeout value (in seconds) for each download operation.<br>@property (nonatomic, assign) NSTimeInterval downloadTimeout;<br>/// The session configuration, it&#39;s immutable after the downloader instance initialized. <br>@property (nonatomic, strong, nullable) NSURLSessionConfiguration *sessionConfiguration;<br>/// Passing `NSOperation&lt;SDWebImageDownloaderOperation&gt;` to set as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`.<br>@property (nonatomic, assign, nullable) Class operationClass;<br>/// The download operations execution order, default is FIFO<br>@property (nonatomic, assign) SDWebImageDownloaderExecutionOrder executionOrder;</pre><p>the <strong>requestModifier</strong>, provide modification before download request</p><pre>/// Modify the original URL request and return a new one instead. You can modify the HTTP header, cachePolicy, etc for this URL.<br>@protocol SDWebImageDownloaderRequestModifier &lt;NSObject&gt;<br>   <br>- (nullable NSURLRequest *)modifiedRequestWithRequest:(nonnull NSURLRequest *)request;<br><br>@end</pre><p>Similarly, the <strong>responseModifier</strong> provides modification of the return value</p><pre>/// Modify the original URL response and return a new response. You can use this to check MIME-Type, mock server response, etc.<br><br>@protocol SDWebImageDownloaderResponseModifier &lt;NSObject&gt;<br><br>- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response;<br><br>@end</pre><p>The last <strong>decryptor</strong> is used for image decryption, which provides base64 conversion of imageData by default.</p><pre>/// Decrypt the original download data and return a new data. You can use this to decrypt the data using your perfereed algorithm.<br>@protocol SDWebImageDownloaderDecryptor &lt;NSObject&gt;<br><br>- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response;<br><br>@end</pre><p>Processing data through these protocoled objects origins the <a href="https://www.wikiwand.com/en/Strategy_pattern"><strong>strategy pattern</strong></a>. By obtaining the protocol object through configuration, the caller only needs to care about the method provided by the protocol object, and does not need to care about its internal implementation to achieve the purpose of decoupling.</p><h4>DownloadImageWithURL</h4><p>Before downloading, check whether the URL exists.</p><p>If not, directly throw an error and return. After getting the URL, try to reuse the operation generated before:</p><pre>NSOperation&lt;SDWebImageDownloaderOperation&gt; *operation = [self.URLOperations objectForKey:url];</pre><p>If operation exists, call</p><pre>@synchronized (operation) {<br>    downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock];<br>}</pre><p>And set the queuePriority. Here the @synchronized (operation) is used to compare the @synchronized (self), which is used inside the operation to ensure the thread safety of the operation between two different classes. Because the operation may be passed to the decoding or proxy queue.</p><p>Then addHandlersForProgres method will save progressBlock and completedBlock into NSMutableDictionary &lt;NSString *, id&gt; SDCallbacksDictionary and then return and save it into downloadOperationCancelToken.</p><p>In addition, operation in addHandlersForProgress method does not clear the previous stored callbacks. They are saved incrementally, which means that all the callBacks will be executed in sequence after download completion.</p><p>If the operation is nil、isFinished or isCancelled will call createDownloaderOperationWithUrl:options:context: to create a new operation and store it in URLOperations and configure completionBlock. So that URLOperations can be cleared when the task is completed. Then call addHandlersForProgress:completed: to save progressBlock and completedBlock. At last submit operation to the downloadQueue.</p><p>The final operation, url, request, and downloadOperationCancelToken are packaged into <strong>SDWebImageDownloadToken</strong>, which the end of the download task.</p><h4>CreateDownloaderOperation</h4><p>After downloading, let’s talk about how the operation is created. The first is to generate a URLRequest:</p><p>It is mainly configured by obtaining parameters through SDWebImageDownloaderOptions. The timeout is determined by downloader’s config.downloadTimeout, the default is 15s.</p><p>Then remove id &lt;SDWebImageDownloaderRequestModifier&gt; requestModifier from imageContext to transform the request.</p><p>What you need to pay attention to is that the access to requestModifier has <strong>priority</strong>, and the priority obtained through imageContext is higher than the downloader. This kind of method not only satisfies the controllability of the caller, but also supports the global configuration, which is suitable for all ages.</p><p>Similarly, id &lt;SDWebImageDownloaderResponseModifier&gt; responseModifier and id &lt;SDWebImageDownloaderDecryptor&gt; decryptor are also the same approach.</p><p>After that, the confirmed responseModifier and decryptor will be saved in imageContext again for later use.</p><p>Finally, remove operationClass from downloaderConfig to create operation:</p><pre>Class operationClass = self.config.operationClass;<br>if (operationClass &amp;&amp; [operationClass isSubclassOfClass:[NSOperation class]] &amp;&amp; [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperation)]) {<br>    // Custom operation class<br>} else {<br>    operationClass = [SDWebImageDownloaderOperation class];<br>}<br>NSOperation&lt;SDWebImageDownloaderOperation&gt; *operation = [[operationClass alloc] initWithRequest:request inSession:self.session options:options context:context];</pre><p>Set the <em>credential, minimumProgressInterval, queuePriority, pendingOperation</em>.</p><p>By default, each task is added to the downloadQueue in FIFO order. If you set it as LIFO, the task priority will be modified before adding to the queue:</p><pre>if (self.config.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {<br>    // Emulate LIFO execution order by systematically, each previous adding operation can dependency the new operation<br>    // This can gurantee the new operation to be execulated firstly, even if when some operations finished, meanwhile you appending new operations<br>    // Just make last added operation dependents new operation can not solve this problem. See test case #test15DownloaderLIFOExecutionOrder<br>    for (NSOperation *pendingOperation in self.downloadQueue.operations) {<br>        [pendingOperation addDependency:operation];<br>    }<br>}</pre><h4>Data Processing</h4><p>SDWebImageDownloaderOperation is also a protocolization class, which confirm NSURLSessionTaskDelegate, NSURLSessionDataDelegate. It handles URL request data, supports background downloading, supports responseData modification (by responseModifier), and supports download ImageData decryption (by decryptor). The main internal properties are as follows:</p><pre>@property (assign, nonatomic, readwrite) SDWebImageDownloaderOptions options;<br>@property (copy, nonatomic, readwrite, nullable) SDWebImageContext *context;<br>@property (strong, nonatomic, nonnull) NSMutableArray&lt;SDCallbacksDictionary *&gt; *callbackBlocks;<br><br>@property (strong, nonatomic, nullable) NSMutableData *imageData;<br>@property (copy, nonatomic, nullable) NSData *cachedData; // for `SDWebImageDownloaderIgnoreCachedResponse`<br>@property (assign, nonatomic) NSUInteger expectedSize; // may be 0<br>@property (assign, nonatomic) NSUInteger receivedSize;<br><br>@property (strong, nonatomic, nullable) id&lt;SDWebImageDownloaderResponseModifier&gt; responseModifier; // modifiy original URLResponse<br>@property (strong, nonatomic, nullable) id&lt;SDWebImageDownloaderDecryptor&gt; decryptor; // decrypt image data<br>// This is weak because it is injected by whoever manages this session. If this gets nil-ed out, we won&#39;t be able to run<br>// the task associated with this operation<br>@property (weak, nonatomic, nullable) NSURLSession *unownedSession;<br>// This is set if we&#39;re using not using an injected NSURLSession. We&#39;re responsible of invalidating this one<br>@property (strong, nonatomic, nullable) NSURLSession *ownedSession;<br><br>@property (strong, nonatomic, nonnull) dispatch_queue_t coderQueue; // the queue to do image decoding<br>#if SD_UIKIT<br>@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;<br><br>- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request<br>                              inSession:(nullable NSURLSession *)session<br>                                options:(SDWebImageDownloaderOptions)options<br>                                context:(nullable SDWebImageContext *)context;</pre><p>There is nothing special about initialization. You should noted that the nullable session passed here is saved with unownedSession, which is different from the <strong>ownedSession</strong> generated by default internally. If the session is empty during initialization, the ownedSession will be created at start.</p><p>Then the problem is coming, because we need to observe the various states of the session, we need to set up the delegate.</p><pre>[NSURLSession sessionWithConfiguration: delegate:delegateQueue:];</pre><p>The delegate of the ownedSession is undoubtedly inside the operation, while the delegate of unownedSession is the downloader. It will retrieve the operation through taskID and forwarding of the callback through the operation’s delegate. Here is the code:</p><pre>- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {<br>    <br>    // Identify the operation that runs this task and pass it the delegate method<br>    NSOperation&lt;SDWebImageDownloaderOperation&gt; *dataOperation = [self operationWithTask:task];<br>    if ([dataOperation respondsToSelector:@selector(URLSession:task:didCompleteWithError:)]) {<br>        [dataOperation URLSession:session task:task didCompleteWithError:error];<br>    }<br>}</pre><p>Then, as a real consumer operation trigger the download task. The entire download process including start, end, and cancellation will send corresponding notifications.</p><ol><li>In <strong>didReceiveResponse</strong>, response.expectedContentLength will be saved as expectedSize. Then call modifiedResponseWithResponse: to save the edited response.</li><li>Every time <strong>didReceiveData</strong> will append data to imageData: [self.imageData appendData: data], update receivedSize self.receivedSize = self.imageData.length. Finally, when receivedSize bigger than expectedSize, which means the download task is completed, and move to the next stage. If you support SDWebImageDownloaderProgressiveLoad, you will be able to decoding while downloading in coderQueue:</li></ol><pre>// progressive decode the image in coder queue<br>dispatch_async(self.coderQueue, ^{<br>    @autoreleasepool {<br>        UIImage *image = SDImageLoaderDecodeProgressiveImageData(imageData, self.request.URL, finished, self, [[self class] imageOptionsFromDownloaderOptions:self.options], self.context);<br>        if (image) {<br>            // We do not keep the progressive decoding image even when `finished`=YES. Because they are for view rendering but not take full function from downloader options. And some coders implementation may not keep consistent between progressive decoding and normal decoding.<br>            <br>            [self callCompletionBlocksWithImage:image imageData:nil error:nil finished:NO];<br>        }<br>    }<br>});</pre><p>4. Otherwise, the decoding operation will be completed when <strong>didCompleteWithError</strong>: SDImageLoaderDecodeImageData, but you need to decrypt it before decoding:</p><pre>if (imageData &amp;&amp; self.decryptor) {<br>    imageData = [self.decryptor decryptedDataWithData:imageData response:self.response];<br>}</pre><p>​ 3. Handle the complete callback;</p><p><em>We will talk about the logic of decode finally.</em></p><p>The design of Cache classes are consistent with the ImageLoader. There will be a <strong>SDImageCacheConfig</strong> to configure the cache expiration time, capacity, read and write permissions, and dynamically MemoryCache / DiskCache class.</p><p>The main properties of SDImageCacheConfig are as follows:</p><pre>@property (assign, nonatomic) BOOL shouldDisableiCloud;<br>@property (assign, nonatomic) BOOL shouldCacheImagesInMemory;<br>@property (assign, nonatomic) BOOL shouldUseWeakMemoryCache;<br>@property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenEnterBackground;<br>@property (assign, nonatomic) NSDataReadingOptions diskCacheReadingOptions;<br>@property (assign, nonatomic) NSDataWritingOptions diskCacheWritingOptions;<br>@property (assign, nonatomic) NSTimeInterval maxDiskAge;<br>@property (assign, nonatomic) NSUInteger maxDiskSize;<br>@property (assign, nonatomic) NSUInteger maxMemoryCost;<br>@property (assign, nonatomic) NSUInteger maxMemoryCount;<br>@property (assign, nonatomic) SDImageCacheConfigExpireType diskCacheExpireType;<br>/// Defaults to built-in `SDMemoryCache` class.<br>@property (assign, nonatomic, nonnull) Class memoryCacheClass;<br>/// Defaults to built-in `SDDiskCache` class.<br>@property (assign ,nonatomic, nonnull) Class diskCacheClass;</pre><p>MemoryCache and DiskCache instantiation depends on SDImageCacheConfig:</p><pre>/**<br> A memory cache which auto purge the cache on memory warning and support weak cache.<br> */<br>@interface SDMemoryCache &lt;KeyType, ObjectType&gt; : NSCache &lt;KeyType, ObjectType&gt; &lt;SDMemoryCache&gt;<br><br>@property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config;<br><br>@end</pre><p>As a cache protocol, their interface declarations are basically the same, all of which are CURD for data. The difference is that MemoryCache Protocol operates on the <strong>id</strong> type (NSCache’s limitation), and DiskCache is on NSData.</p><h3>SDMemoryCache</h3><pre>/**<br> A memory cache which auto purge the cache on memory warning and support weak cache.<br> */<br>@interface SDMemoryCache &lt;KeyType, ObjectType&gt; : NSCache &lt;KeyType, ObjectType&gt; &lt;SDMemoryCache&gt;<br><br>@property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config;<br><br>@end</pre><p>Internally, <strong>NSCache</strong> is the implementation for SDMemoryCache, and add <strong>NSMapTable &lt;KeyType, ObjectType&gt; * weakCache</strong> property, which use semaphore lock to ensure thread safety. The weak-cache is a feature added only on the <em>iOS / tvOS</em> platform, because on macOS, NSCache will not clear the corresponding cache, when receiving system memory warning. WeakCache uses strong-weak references without additional memory overhead and does not affect the life cycle of the object.</p><p>The role of weakCache is to restore the cache. It is controlled by the <strong>shouldUseWeakMemoryCache</strong> switch of CacheConfig. For details, you can check the <a href="https://github.com/SDWebImage/SDWebImage/blob/master/SDWebImage/Core/SDImageCacheConfig.h">CacheConfig</a>.</p><p>First, look at how <em>objectForKey</em> is implemented:</p><pre>- (id)objectForKey:(id)key {<br>    id obj = [super objectForKey:key];<br>    if (!self.config.shouldUseWeakMemoryCache) {<br>        return obj;<br>    }<br>    if (key &amp;&amp; !obj) {<br>        // Check weak cache<br>        SD_LOCK(self.weakCacheLock);<br>        obj = [self.weakCache objectForKey:key];<br>        SD_UNLOCK(self.weakCacheLock);<br>        if (obj) {<br>            // Sync cache<br>            NSUInteger cost = 0;<br>            if ([obj isKindOfClass:[UIImage class]]) {<br>                cost = [(UIImage *)obj sd_memoryCost];<br>            }<br>            [super setObject:obj forKey:key cost:cost];<br>        }<br>    }<br>    return obj;<br>}</pre><p>Since NSCache follows NSDiscardableContent to store temporary objects. When the memory is tight, the cached objects may be cleaned up by the system. At this time, once the application accesses MemoryCache and the cache missing, which will be transferred to the diskCache query operation. And that may cause the image to flicker. And when shouldUseWeakMemoryCache is true, because weakCache holds the weak reference of the object (when the object is cleaned by NSCache but not released), we can get the cache by weakCache and stuff it into NSCache, which will reduces disk I/O.</p><h3>SDDiskCache</h3><p>This is simpler, internally uses NSFileManager to manage the reading and writing of image data, and calls SDDiskCacheFileNameForKey to process the key MD5 as fileName and store it in the diskCachePath directory. The other is to clear the expired cache:</p><ol><li>Sort by SDImageCacheConfigExpireType to get NSDirectoryEnumerator * fileEnumerator and start filtering;</li><li>Use cacheConfig.maxDiskAage to determine whether it is expired, and store the expired URL in urlsToDelete;</li><li>Call [self.fileManager removeItemAtURL: fileURL error: nil];</li><li>According to cacheConfig.maxDiskSize to delete the data cached on the disk, clean up to 1/2 of maxDiskSize.</li></ol><p>By the way, SDDiskCache, like <a href="https://github.com/ibireme/YYCache/blob/master/YYCache/YYKVStorage.h"><strong>YYKVStorage</strong></a>, also supports adding extendData to UIImage to store additional information, for example, the zoom ratio of the picture, <a href="https://sspai.com/post/55279">URL rich link</a>, time And other data.</p><p>However, **YYKVStorage **store the extended_data field by the <strong><em>manifest</em></strong> table in the database. SDDiskCache solution is a different way, by use system API &lt;sys/xattr.h&gt; **setxattr **, **getxattr **, <strong>listxattr</strong> to save extendData, which is really amazing. One more thing, the corresponding key is <em>SDDiskCacheExtendedAttributeName</em>.</p><h3>SDImageCache</h3><p>It is also a protocold class, which is responsible for scheduling SDMemoryCache and SDDiskCache, and its Properties are as follows:</p><pre>@property (nonatomic, strong, readwrite, nonnull) id&lt;SDMemoryCache&gt; memoryCache;<br>@property (nonatomic, strong, readwrite, nonnull) id&lt;SDDiskCache&gt; diskCache;<br>@property (nonatomic, copy, readwrite, nonnull) SDImageCacheConfig *config;<br>@property (nonatomic, copy, readwrite, nonnull) NSString *diskCachePath;<br>@property (nonatomic, strong, nullable) dispatch_queue_t ioQueue;</pre><blockquote><em>Note: The memoryCache and diskCache instances are generated according to the class defined in CacheConfig, and the defaults are SDMemoryCache and SDDiskCache.</em></blockquote><p>Let’s take a look at its core method:</p><pre>- (void)storeImage:(nullable UIImage *)image<br>         imageData:(nullable NSData *)imageData<br>            forKey:(nullable NSString *)key<br>          toMemory:(BOOL)toMemory<br>            toDisk:(BOOL)toDisk<br>        completion:(nullable SDWebImageNoParamsBlock)completionBlock;</pre><ol><li>Make sure that image and key exist;</li><li>When <strong>shouldCacheImagesInMemory</strong> is YES, it calls [self.memoryCache setObject:image forKey:key cost:cost] to write memoryCache;</li><li>Write diskCache, put the operation logic into ioQueue and autoreleasepool.</li></ol><pre>dispatch_async(self.ioQueue, ^{<br>    @autoreleasepool {<br>        NSData *data = ... // 根据 SDImageFormat 对 image 进行编码获取<br>        /// data = [[SDImageCodersManager sharedManager] encodedDataWithImage:image format:format options:nil];<br>        [self _storeImageDataToDisk:data forKey:key];<br>        if (image) {<br>            // Check extended data<br>            id extendedObject = image.sd_extendedObject;<br>            // ... get extended data<br>            [self.diskCache setExtendedData:extendedData forKey:key];<br>        }<br>    }<br>    // call completionBlock in main queue<br>});</pre><p>Another important method is image query, which is defined in the SDImageCache protocol:</p><pre>- (id&lt;SDWebImageOperation&gt;)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock {<br>    SDImageCacheOptions cacheOptions = 0;<br>    if (options &amp; SDWebImageQueryMemoryData) cacheOptions |= SDImageCacheQueryMemoryData;<br>    if (options &amp; SDWebImageQueryMemoryDataSync) cacheOptions |= SDImageCacheQueryMemoryDataSync;<br>    if (options &amp; SDWebImageQueryDiskDataSync) cacheOptions |= SDImageCacheQueryDiskDataSync;<br>    if (options &amp; SDWebImageScaleDownLargeImages) cacheOptions |= SDImageCacheScaleDownLargeImages;<br>    if (options &amp; SDWebImageAvoidDecodeImage) cacheOptions |= SDImageCacheAvoidDecodeImage;<br>    if (options &amp; SDWebImageDecodeFirstFrameOnly) cacheOptions |= SDImageCacheDecodeFirstFrameOnly;<br>    if (options &amp; SDWebImagePreloadAllFrames) cacheOptions |= SDImageCachePreloadAllFrames;<br>    if (options &amp; SDWebImageMatchAnimatedImageClass) cacheOptions |= SDImageCacheMatchAnimatedImageClass;<br>    <br>    return [self queryCacheOperationForKey:key options:cacheOptions context:context done:completionBlock];<br>}</pre><p><strong>queryImageForKey</strong> converts SDWebImageOptions to SDImageCacheOptions, then call queryCacheOperationForKey:, which logic is as follows:</p><p>First, First, if the query key exists, the transformer will be obtained from the imageContext and the query key will be converted:</p><pre>key = SDTransformedKeyForKey(key, transformerKey);</pre><p>Try to get the image from the memory cache, if it exists:</p><ol><li>If SDImageCacheDecodeFirstFrameOnly is satisfied and comforts to SDAnimatedImage protocol, CGImage will be taken out for conversion</li></ol><pre>// Ensure static image<br>Class animatedImageClass = image.class;<br>if (image.sd_isAnimated || ([animatedImageClass isSubclassOfClass:[UIImage class]] &amp;&amp; [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)])) {<br>#if SD_MAC<br>    image = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp];<br>#else<br>    image = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation];<br>#endif<br>}</pre><p>2. If SDImageCacheMatchAnimatedImageClass is satisfied, it will be forced to check whether the image type matches, otherwise the data will be nil:</p><pre>// Check image class matching<br>Class animatedImageClass = image.class;<br>Class desiredImageClass = context[SDWebImageContextAnimatedImageClass];<br>if (desiredImageClass &amp;&amp; ![animatedImageClass isSubclassOfClass:desiredImageClass]) {<br>    image = nil;<br>}</pre><p>When the image can be obtained from the memory cache and is SDImageCacheQueryMemoryData, return directly, otherwise continue;</p><p>Start reading diskCache, and use shouldQueryDiskSync to specify query cache sync/async behavior.</p><pre>// Check whether we need to synchronously query disk<br>// 1. in-memory cache hit &amp; memoryDataSync<br>// 2. in-memory cache miss &amp; diskDataSync<br>BOOL shouldQueryDiskSync = ((image &amp;&amp; options &amp; SDImageCacheQueryMemoryDataSync) ||<br>                            (!image &amp;&amp; options &amp; SDImageCacheQueryDiskDataSync));</pre><p>The entire diskQuery is stored in queryDiskBlock and wrapped with autorelease:</p><pre>void(^queryDiskBlock)(void) =  ^{<br>    if (operation.isCancelled) {<br>        // call doneBlock &amp; return<br>    }<br>    @autoreleasepool {<br>        NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];<br>        UIImage *diskImage;<br>        SDImageCacheType cacheType = SDImageCacheTypeNone;<br>        if (image) {<br>            // the image is from in-memory cache, but need image data<br>            diskImage = image;<br>            cacheType = SDImageCacheTypeMemory;<br>        } else if (diskData) {<br>            cacheType = SDImageCacheTypeDisk;<br>            // decode image data only if in-memory cache missed<br>            diskImage = [self diskImageForKey:key data:diskData options:options context:context];<br>            if (diskImage &amp;&amp; self.config.shouldCacheImagesInMemory) {<br>                NSUInteger cost = diskImage.sd_memoryCost;<br>                [self.memoryCache setObject:diskImage forKey:key cost:cost];<br>            }<br>        }<br>        // call doneBlock<br>        if (doneBlock) {<br>            if (shouldQueryDiskSync) {<br>                doneBlock(diskImage, diskData, cacheType);<br>            } else {<br>                dispatch_async(dispatch_get_main_queue(), ^{<br>                    doneBlock(diskImage, diskData, cacheType);<br>                });<br>            }<br>        }<br>    }<br>}</pre><p>For large amounts of temporary memory operations, SD will put it into autoreleasepool to ensure that the memory can be released in time.</p><p><strong>Special emphasis</strong>, once the code is executed here, there must be disk querying operations, so if you don’t have to get imageData, you can use <strong>SDImageCacheQueryMemoryData</strong> to improve query efficiency.</p><p>One more thing, the conversion logic of SDTransformedKeyForKey is the transformerKey of <strong>SDImageTransformer</strong>, which is spliced behind the image key in order. E.g:</p><pre>&#39;image.png&#39; |&gt; flip(YES,NO) |&gt; rotate(pi/4,YES)  =&gt; <br>&#39;image-SDImageFlippingTransformer(1,0)-SDImageRotationTransformer(0.78539816339,1).png&#39;</pre><p>SDWebImageManager serves as the dispatch center of the entire library, who is the master of the above various logics. It connects the components in series, from View &gt; Downloading &gt; Decoding &gt; Cache. The only core method it exposes is <strong>loadImage</strong>:</p><pre>@property (strong, nonatomic, readonly, nonnull) id&lt;SDImageCache&gt; imageCache;<br>@property (strong, nonatomic, readonly, nonnull) id&lt;SDImageLoader&gt; imageLoader;<br>@property (strong, nonatomic, nullable) id&lt;SDImageTransformer&gt; transformer;<br>@property (nonatomic, strong, nullable) id&lt;SDWebImageCacheKeyFilter&gt; cacheKeyFilter;<br>@property (nonatomic, strong, nullable) id&lt;SDWebImageCacheSerializer&gt; cacheSerializer;<br>@property (nonatomic, strong, nullable) id&lt;SDWebImageOptionsProcessor&gt; optionsProcessor;<br><br>@property (nonatomic, class, nullable) id&lt;SDImageCache&gt; defaultImageCache;<br>@property (nonatomic, class, nullable) id&lt;SDImageLoader&gt; defaultImageLoader;<br><br>- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url<br>                                                   options:(SDWebImageOptions)options<br>                                                   context:(nullable SDWebImageContext *)context<br>                                                  progress:(nullable SDImageLoaderProgressBlock)progressBlock<br>                                                 completed:(nonnull SDInternalCompletionBlock)completedBlock;</pre><p>Let’s briefly talk about the three left APIs cacheKeyFilter, cacheSerializer and optionsProcessor, the rest of which have been mentioned above.</p><p><strong>SDWebImageCacheKeyFilter</strong></p><p>By default, the URL.absoluteString is used as cacheKey, and if filter is set, cacheKey will be replaced by cacheKeyForURL:;</p><p><strong>SDWebImageCacheSerializer</strong></p><p>By default, ImageCache will directly cache downloadData, and when we use other image formats for transmission, such as WEBP format, then the data with WEBP format will be stored to the disk directly. This will cause a problem, every time when we query the image from the disk, we have to repeat the decoding operation. The CacheSerializer can directly convert downloadData to JPEG / PNG format NSData cache, thereby improving access efficiency.</p><p><strong>SDWebImageOptionsProcessor</strong></p><p>Used to control the global parameters in SDWebImageOptions and SDWebImageContext. E.g:</p><pre>SDWebImageManager.sharedManager.optionsProcessor = [SDWebImageOptionsProcessor optionsProcessorWithBlock:^SDWebImageOptionsResult * _Nullable(NSURL * _Nullable url, SDWebImageOptions options, SDWebImageContext * _Nullable context) {<br>     // Only do animation on `SDAnimatedImageView`<br>     if (!context[SDWebImageContextAnimatedImageClass]) {<br>        options |= SDWebImageDecodeFirstFrameOnly;<br>     }<br>     // Do not force decode for png url<br>     if ([url.lastPathComponent isEqualToString:@&quot;png&quot;]) {<br>        options |= SDWebImageAvoidDecodeImage;<br>     }<br>     // Always use screen scale factor<br>     SDWebImageMutableContext *mutableContext = [NSDictionary dictionaryWithDictionary:context];<br>     mutableContext[SDWebImageContextImageScaleFactor] = @(UIScreen.mainScreen.scale);<br>     context = [mutableContext copy];<br> <br>     return [[SDWebImageOptionsResult alloc] initWithOptions:options context:context];<br> }];</pre><h3>LoadImage</h3><p>The first parameter of the method, the <strong>url</strong>, which serves as the connection core of SD, was designed to be nullable. This design may be for the convenience of users. Internally through the nil judgment of the url and the compatibility with the NSString type (forced conversion to NSURL) to ensure the subsequent process, otherwise the call ends.</p><p>After the download started, it was split into the following 6 methods:</p><ul><li>callCacheProcessForOperation</li><li>callDownloadProcessForOperation</li><li>callStoreCacheProcessForOperation</li><li>callTransformProcessForOperation</li><li>callCompletionBlockForOperation</li><li>safelyRemoveOperationFromRunning</li></ul><p>They are cache query, download, storage, conversion, execution callback, and cleanup callback. You can find that each method is delivered through the operation, which will be ready when the loadImage is loaded, then trigger the cache query.</p><pre>@interface SDWebImageCombinedOperation : NSObject &lt;SDWebImageOperation&gt;<br>/// imageCache queryImageForKey: 的 operation<br>@property (strong, nonatomic, nullable, readonly) id&lt;SDWebImageOperation&gt; cacheOperation;<br>/// imageLoader requestImageWithURL: 的 operation<br>@property (strong, nonatomic, nullable, readonly) id&lt;SDWebImageOperation&gt; loaderOperation;<br>/// Cancel the current operation, including cache and loader process<br>- (void)cancel;<br>@end</pre><p>The implementation of <strong>loadImage</strong> is relatively simple, and the core is to generate an operation then transfer it to a cache query.</p><p>After the operation is initialized, it will checks whether failedURLs contains the current url:</p><ul><li>If yes, and options is SDWebImageRetryFailed, directly return operation and end;</li><li>If pass, the operation will be stored in runningOperations. Enclose options and imageContext in <strong>SDWebImageOptionsResult</strong>.</li></ul><p>then will update imageContext, mainly store the transformer, cacheKeyFilter, cacheSerializer as the global default setting, and then call <strong>optionsProcessor</strong> to fulfill user’s custom options to modify imageContext again.</p><p>If you see here from the front, you should have an impression of this routine. The priority logic of requestModifier in the previous ImageLoader is similar to this, but the implementation is somewhat different. Finally, transfer to CacheProcess.</p><p>The operation of <strong>loadImage</strong> is a combineOperation, which is a combination of cache and loader operation tasks, so that it can clean up the cache query and download tasks in one step. The statement is as follows:</p><pre>@interface SDWebImageCombinedOperation : NSObject &lt;SDWebImageOperation&gt;<br>/// imageCache queryImageForKey: 的 operation<br>@property (strong, nonatomic, nullable, readonly) id&lt;SDWebImageOperation&gt; cacheOperation;<br>/// imageLoader requestImageWithURL: 的 operation<br>@property (strong, nonatomic, nullable, readonly) id&lt;SDWebImageOperation&gt; loaderOperation;<br>/// Cancel the current operation, including cache and loader process<br>- (void)cancel;<br>@end</pre><p>The cancel method provided by it will gradually check two types of opration and then call the cancel operation one by one.</p><h4>CallCacheProcessForOperation</h4><p>First check the value of <strong>SDWebImageFromLoaderOnly</strong> to determine whether need to start the download task directly.</p><p>If yes, forward to downloadProcess.</p><p>Otherwise, create a query task through imageCache and save it to combineOperation&#39;s cacheOperation:</p><pre>operation.cacheOperation = [self.imageCache queryImageForKey:key options:options context:context completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {<br>   if (!operation || operation.isCancelled) {<br>    	/// 1  <br>   }<br>  	/// 2<br>}];</pre><p>There are two situations that need to be handled for the results of the cache query:</p><ol><li>When the operation is executing in the queue and operation was marked as canceled, will end the download task;</li><li>Otherwise, forward to downloadProcess.</li></ol><h4>CallDownloadProcessForOperation</h4><p>The most complex of the 6 methods. First, We need to decide whether we need to create a new download task, which is controlled by three variables:</p><pre>BOOL shouldDownload = !SD_OPTIONS_CONTAINS(options, SDWebImageFromCacheOnly);<br>    shouldDownload &amp;= (!cachedImage || options &amp; SDWebImageRefreshCached);<br>    shouldDownload &amp;= (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]);<br>    shouldDownload &amp;= [self.imageLoader canRequestImageForURL:url];</pre><ul><li>check options value is set as SDWebImageFromCacheOnly or SDWebImageRefreshCached;</li><li>check the delegate method <strong>shouldDownloadImageForURL</strong> value;</li><li>check whether the imageLoader <strong>canRequestImageForURL</strong>;</li></ul><ol><li>If shouldDownload is NO, close the download task. And perform <strong>callCompletionBlockForOperation</strong> and <strong>safelyRemoveOperationFromRunning</strong>. By the way, if cacheImage exists, it will be returned with completionBlock.</li><li>If shouldDownload is YES, create a new download task and save it in combineOperation’s loaderOperation. Before creating a new task, if cacheImage exist and SDWebImageRefreshCached is set, the cacheImage will be stored in imageContext (if not will create a imageContext).</li><li>After downloading, return to callBack, there are several situations to deal with:</li></ol><ul><li>If the operation is canceled, the downloaded image and data will be discarded. And call the completion block and close the download task ;</li><li>Error caused by cancelled reqeust, call the completion block and close the download task ;</li><li>Image refresh hit the NSURLCache cache, do not call the completion block;</li><li>error, <strong>callCompletionBlockForOperation</strong> and add url to failedURLs;</li><li>None of the above conditions, if successful by retry, will remove the url from failedURLs first, call <strong>storeCacheProcess</strong>;</li></ul><p>Finally, call the <strong>safelyRemoveOperation</strong> for operation which marked as finished;</p><h4>CallStoreCacheProcessForOperation</h4><p>Pour out storeCacheType、originalStoreCacheType、transformer、cacheSerializer from imageContext.</p><p>Check if it is necessary to store the converted image data, original data, and wait for the end of the cache storage:</p><pre>BOOL shouldTransformImage = downloadedImage &amp;&amp; (!downloadedImage.sd_isAnimated || (options &amp; SDWebImageTransformAnimatedImage)) &amp;&amp; transformer;<br>BOOL shouldCacheOriginal = downloadedImage &amp;&amp; finished;<br>BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache);</pre><p>If shouldCacheOriginal is NO, directly transfer to <strong>transformProcess</strong>. Otherwise, first confirm whether the storage type is the original data:</p><pre>// normally use the store cache type, but if target image is transformed, use original store cache type instead<br>SDImageCacheType targetStoreCacheType = shouldTransformImage ? originalStoreCacheType : storeCacheType;</pre><p>If cacheSerializer exists during storage, it will first convert the data format, and finally call [self storeImage: ...]</p><p>When the storage is over, go to the last step, <strong>transformProcess</strong>.</p><h4>CallTransformProcessForOperation</h4><p>Before the conversion starts, it will routinely judge whether it needs to be converted.</p><pre>id&lt;SDImageTransformer&gt; transformer = context[SDWebImageContextImageTransformer];<br>id&lt;SDWebImageCacheSerializer&gt; cacheSerializer = context[SDWebImageContextCacheSerializer];<br>BOOL shouldTransformImage = originalImage &amp;&amp; (!originalImage.sd_isAnimated || (options &amp; SDWebImageTransformAnimatedImage)) &amp;&amp; transformer;<br>BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache);</pre><p>If conversion is required, it will enter the global queue to start processing:</p><pre>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{<br>    @autoreleasepool {<br>        UIImage *transformedImage = [transformer transformedImageWithImage:originalImage forKey:key];<br>        if (transformedImage &amp;&amp; finished) {<br>				/// 1<br>        } else {<br>				callCompletionBlock<br>        }<br>    }<br>});</pre><p>After the conversion is successful, the image will be stored according to</p><pre>cacheData = [cacheSerializer cacheDataWithImage: originalData: imageURL:];</pre><p>After storing, call completion block. The end.</p><h3>The End</h3><p>I am honored that you can reach here. I hope you can get a general understanding of the work-flow of SD, as well as some details of processing and thinking. In SD 5.x, the most personal feeling is that the design of its architecture is worth learning.</p><ul><li>How to design a stable and extensible API that can safely support dynamic parameter addition?</li><li>How to design a decoupled and dynamically pluggable architecture?</li></ul><p>Finally, this article actually lacks <strong>SDImageCoder</strong>, which will be left for the next SDWebImage plugin and its extension.</p><p><em>Originally published at </em><a href="http://looseyi.github.io/"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b673044c14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[浅析 Cocoapods-Packager 实现]]></title>
            <link>https://medium.com/@liuedmond/%E6%B5%85%E6%9E%90-cocoapods-packager-%E5%AE%9E%E7%8E%B0-6501ff5ae356?source=rss-d3b3aa852ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6501ff5ae356</guid>
            <category><![CDATA[cocoapods-packager]]></category>
            <category><![CDATA[xcodebuild]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cocoapods]]></category>
            <dc:creator><![CDATA[Liu Edmond]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 07:10:58 GMT</pubDate>
            <atom:updated>2020-04-05T10:58:02.036Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>CocoaPods plugin which allows you to generate a framework or static library from a podspec.</em></blockquote><blockquote><em>This plugin is for CocoaPods </em>developers<em>, who need to distribute their Pods not only via CocoaPods, but also as frameworks or static libraries for people who do not use Pods.</em></blockquote><p>作为 CococaPods 的官方插件之一，CocoaPods Packager 为 Pod 提供了 <strong>package</strong> 命令来生成 framework or static library。你可以仅凭一个 podspec 文件就能完成一个 framework 或 library 的生成。</p><p>那 Packager 的使用场景有哪些？网上有特别多详细的使用说明文档，而分析实现的比较少。这也是这篇文章的初衷，想知道它是如何 work 的。本身插件也不是很复杂，这里会更挖一些细节。之前简单写了一篇文章： <a href="https://juejin.im/post/5dfdfcc76fb9a0165835acc6">浅析 Cocoapods-Binary 实现</a> ，主要是这两个插件的核心逻辑类似，感兴趣的可以拿来对比。它们的区别在于 package 的对象是针对单个 pod 还是整个 project 的。</p><h3>CocoaPods Plugins</h3><p>这次我们先简单谈一谈 CococaPods 的插件原理。作为一款社区产品，仅有的少数核心开发者是无法满足大量开发者的各种需求。因此，在 <a href="https://blog.cocoapods.org/CocoaPods-0.28/">2013 CcocoaPods 开始支持 Plugins</a> 扩展，使得大家可以自行支持所需要的功能。</p><h3>What can CocoaPods Plugins do?</h3><ul><li>可以 Hook pod install 过程，包括 pre_install 与 post_install；</li><li>可以添加新的 pod 命令；</li><li>Ruby 作为 dynamic language，你完全可以随心所欲；</li></ul><h3>RubyGems</h3><p>开始解释源码钱，需要说一说包管理，不得不提 RubyGems 和 Bundler。CocoaPods 背后的原型就是基于它们俩，当然也会参照其他语言的包管理工具如 npm、Gradle。</p><blockquote><em>RubyGems is a hosted ruby library service. It centralizes where you look for a library, and installing ruby libraries / apps.</em></blockquote><blockquote><em>Bundler provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.</em></blockquote><blockquote><em>Bundler is an exit from dependency hell, and ensures that the gems you need are present in development, staging, and production. Starting work on a project is as simple as bundle install.</em></blockquote><p>RubyGems 是为 ruby library 提供集中代码托管的服务。Bundler 则是针对当前项目来管理 Gem 版本的工具，</p><p>Bundler 依据项目中的 <a href="https://bundler.io/v2.0/gemfile.html">Gemfiles</a> 文件来管理 Gem，就好比 CocoaPods 通过 Podfile 来管理 Pod 的版本一样。Gemfile 长这样：</p><p>很熟悉的感觉，有木有。是的，Podfile 的 DSL 和 Gemfile 如出一辙。</p><p>那什么情况会用到 Gemfile 呢？比如，公司级项目中可以通过 gemfile 来统一 CocoaPods 的版本，不然大家各自为政会导致提交代码会因为 CocoaPods 版本不同导致对项目的配置产生各种差异，导致最终的 PR 有大量 conflict 或 change，当然还可以管理 CocoaPods 的插件版本，可以指向你自己的定制版本。</p><p>Bundle 的使用也很简单，在 gem install bundler 后，通过添加 bundle exec 前缀来执行 pod 命令。这时会读取安装在本地 .bundle/ 目录或全局目录下所指定的 Gem 包来执行 pod 命令。</p><p><a href="https://guides.rubygems.org/what-is-a-gem/"><strong>Gem</strong></a></p><blockquote><em>The software package is called a “gem” which contains a packaged Ruby application or library.</em></blockquote><p>Gem 则是包含 Ruby 代码的 application 或者 library，而它就是我们今天的主角，CocoaPods Plugin 背后的支柱。应该说 CocoaPods Plugin 本质上就是 Gem。</p><p>那我们来看一眼 Gem 的文件结构：</p><ul><li>bin：可执行文件目录，当 gem install 的时候，会被加载到用户的 <strong>PATH</strong> 路径下；</li><li>lib：gem 的源代码目录；</li><li>sepc：gem 的测试代码目录；</li><li>Rakefile：是自动化测试程序 <a href="https://rubygems.org/gems/rake">rake</a> 的配置文件，也可用于生成代码或者其他任务；</li><li>gemspec：描述了 gem 的关键信息，下面会提到；</li></ul><blockquote><em>The gemspec specifies the information about a gem such as its name, version, description, authors and homepage.</em></blockquote><p>既然 CocoaPods 也是 Gem，它的 GemSpec 包含哪些信息呢：</p><p>依据那么熟悉的感觉，如果你有搞过 Pod library 的话。PodSpec 类比 Gemspec，就不多介绍了。</p><h3>CocoaPods Plugins</h3><p>了解完 Gem，再看 Plugins 会清晰很多。作为 CocoaPods 的 Plugin，CocoaPods 为我们提供了方便生成 plugin 模版的命令。</p><p>生成 plugin 模版的文件目录与 gem 相差无几，这里直接贴 cocoapods-packager 的文件目录：</p><p>确实没啥特别的，只不过会在 gemfile 中，帮你指定好 cocoapods 的依赖，以及根据提供的 NAME 来生成通用文件。</p><h3>CocoaPods Packager</h3><p>接下来我们提到的文件都是在 lib 文件夹下，即 Packager 的源代码所在地。开始前照例看一下脑图，有一个整体的认识：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IC46qSQmw4QXuTLd.jpg" /></figure><p>这里基本对应了 Packager 的主要文件，作者已经分的比较清楚了，整个 Package 的入口是 /lib/pod/command/package.rb 文件，对应脑图的 Command Run 分类。各个分类下面对应的就是各个文件内部提供的主要方法，接下来我们就从 Package 文件说起。</p><h3>Package</h3><p>本文 Demo 所展示的是基于 Packager 内部提供的测试 spec 来做示例，启动命令如下：</p><blockquote>PS：调试所用的工具是 VSCode，如果你没有用过，绝对不要错过了。</blockquote><p>执行上面代码前，我们需要先在 package.rb 的 initialize 方法内打个断点。然后我们来看 Package 类：</p><p>Package Command 继承自 CocoaPods 内部所提供的命令工具模块 <a href="https://github.com/CocoaPods/CLAide">CLAide</a>::Command。所有扩展 Pod 的命令都需要继承它，同时需要重载它的 options、 validate、 initialize 和 run 四个方法。</p><h4><strong>options</strong></h4><blockquote><em>A list of option name and description tuples.</em></blockquote><p>执行命令所需的可选参数，是 [Array&lt;Array&gt;] 的元组，由参数和对应的描述组成，选项如下：</p><h4><strong>validate</strong></h4><p>校验所传参数有效性，如果参数中带有 --help 选项，则会直接抛出帮助提示。它会在 run 方法执行前被调用。重载前需要先调用 super ，代码如下：</p><p><strong>initialize</strong></p><p>解析参数，然后初始化打包所需的变量。这里着重介绍几个核心参数：</p><ul><li>@config：xcodebuild configuration，值为 <em>Debug</em>、<em>Release</em>，当然也可以自定义，默认为 <em>Release</em>；</li><li>@package_type：所生成的包类型，可以是静态库或者动态库，默认为 static_framework;</li><li>@subspecs：支持所打出的包仅包含部分的 subspec，如果对 subspes 有兴趣，请转<a href="https://guides.cocoapods.org/syntax/podspec.html#group_subspecs">官方文档</a>；</li><li>@exclude_deps：打包的时候踢除 dependencies 的符号表，配合 --no-mangle 一起使用，解决静态库打包时有其他静态库依赖的问题；</li><li>@mangle：是否开自动修改类名等符号，默认开启。</li></ul><p>这里稍微展开一下 <strong>@package_type</strong> ，它其实是由多个参数来决定的，--embeded、--dynamic、--library ：</p><p>可能有部分同学对于 framework 和 libray 的概念比较模糊，这里再说一句，详细可以看 <a href="https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html">Apple Doc</a>:</p><blockquote><em>A </em>framework<em> is a hierarchical directory that encapsulates shared resources, such as a dynamic shared library, nib files, image files, localized strings, header files, and reference documentation in a single package.</em></blockquote><p>简单来说 framework 就一文件夹，你要说和 Bundle 一样也无妨。它是静态库还是动态库，重点看它所包含的 library 类型。如果包含的是 static share library 那就是 static_framework。如果包含的是 dynamic share library 则是 dynamic_framework。而我们平时说的 libxxx.a 则是静态库。</p><h4><strong>run</strong></h4><p>run 方法作为入口比较简单，首先就是检查是否取到所要编译的 podspec 文件。然后针对它创建对应的 working_directory 和 target_directory 。</p><p>working_directory 为打包所在的临时目录，like this：</p><p>target_directory 为最终生成 package 的所在目录，是当前 source code 目录下新开的：</p><p>在 create_working_directory 后，会主动切换当前 ruby 的运行目录至 working_directory 目录下，正式开始编译。 build_package 结束后，将编译产物 copy 到 target_directory 下，同时切换回最初执行命令所在目录 @source_dir 。</p><h4><strong>build_package</strong></h4><p>首先，创建一个 <a href="https://github.com/CocoaPods/cocoapods-packager/blob/461686593c521796c723fe5f1c460e2aa2adbe55/lib/cocoapods-packager/spec_builder.rb">SpecBuilder</a>，其作用是用于生成描述最终产物的 podspec 文件，SpecBuilder 就是一个模版文件生成器。bundler 调用 spec_metadata 方法遍历指定的 podspec 文件复刻出对应的配置并返回新生成的 podspec 文件。</p><p>然后，根据 target 所支持的 platform，iOS / Mac / Watch 依次执行 build_in_sandbox 编译，同时将 platform 信息写入 newspec，以 iOS 为例：</p><p>最后，将 podspec 写入 target_directory 编译结束。</p><h4><strong>build_in_sandbox</strong></h4><p><strong>Config</strong></p><p>首先， config 与 <strong>initialize</strong> 的属性 @config 完全是两个东西，@config 只是一个 ‘Debug’ or ‘Release’ 的字符串，而这里的 config 是 Pod::Config 的实例，默认读取自 ~/.cocoapods/config.yaml 目录下的配置。</p><p>Package 在这里指定了 config 的安装目录 working_dirctory 和沙盒目录 ./Pods。<a href="https://github.com/CocoaPods/CocoaPods/blob/master/lib/cocoapods/config.rb"><strong>Config</strong></a> 类是保存在 /path/to/cocoapods/lib/cocoapods/config.rb 中。它非常重要，包括我们 CocoaPods 平时的 install 过程以及这个 Package 的 build 过程均是读取的全局的 config。作为全局需要访问的对象，一定是个 share instance 咯。在 CocoaPods 中是这么实现的；</p><p>各个模块通过 include 来引入，比如 Command 类中：</p><p>然后就能愉快的使用了。</p><p>有了 config 之后，就可以创建沙盒来执行 pod install。install 过程会针对 static 和 dynamic 分别 install 一次。最后，基于安装后的工程，创建 builder 开始最终的构建操作。沙盒创建和 install 是在 pod_utils.rb ，build 在 builder.rb 中，接下来会单独展开。</p><h3>Pod Utils</h3><p>整个 pods_utils 文件均声明为 Package 的 private 方法，主要做的是 build sandbox 和 pod install。install 会区分 static 和 dynamic。按照 build_in_sandbox 调用顺序展开聊聊。</p><h4>build_static_sandbox</h4><p>通过 Pathname 先生成 static_sandbox_root ，然后返回 Sandbox.new(static_sandbox_root)。static_sandbox_root 会根据参数 dynamic 来判断，是否需要创建二级目录 /static ：</p><p>这么区分是由于，如果为动态库，还会生成一个 dynamic sandbox，其 path 为：</p><p>介绍一下 <a href="https://github.com/CocoaPods/CocoaPods/blob/master/lib/cocoapods/sandbox.rb">SandBox</a> ，其定义如下：</p><blockquote><em>The sandbox provides support for the directory that CocoaPods uses for an installation. In this directory the Pods projects, the support files and the sources of the Pods are stored.</em></blockquote><p>所以，sandbox 就是用于管理 pod install 目录。</p><h4>install_pod</h4><p>既然是 pod install 当然需要来一个 podfile 了。package 会根据指定的 spec 来手动创建 podfile。</p><p>我们知道 Podfile 作为 DSL 文件，其每一行配置背后都对应具体的方法，上面的这个就是简化版的 podfile 对应的命令，options 就是我们配置的 pod 方法所需的参数，对应的是： pod(spec_name, options) 。反转过来对对应的 podfile DSL 应该是这样的：</p><p>这里如果参数中指定了 path 则不会通过 spec 指定的 source 去download 源码下来。</p><p>接着就是 pod install 了：</p><p>这里重点就是 build_settings 的两个配置。当 static_installer install 成功后会修改它们，作用是为了支持后续dynamic_framework 的编译。 GCC_GENERATE_DEBUGGING_SYMBOLS 这个 config 应该都知道吧？</p><p>我们来看另一个 <strong>CLANG_MODULES_AUTOLINK</strong>，在 stackoverflow 上有一个 <a href="https://stackoverflow.com/questions/42646716/how-is-a-blank-new-cocoa-app-project-linking-with-the-system-frameworks">解释</a>:</p><blockquote><em>When you create a new project, Xcode will set the </em><em>Link Frameworks Automatically flag to YES. Then the clang linking flag will be set to </em><em>CLANG_MODULES_AUTOLINK = YES. With this option, clang will linking the framework for you automatically.</em></blockquote><p>就是为了避免 install 后，项目 autolink。</p><h4>install_dynamic_pod</h4><p>build_dynamic_sandbox 前面已经说过了，我们直接看动态库的 install：</p><p>内部分了 6 个方法，还附带了详细的注释。需要注意的是，整个 install_dynamic_pod 是基于 install_pod 所生成的 static_installer 来修改的。这里比较复杂，一步步来。</p><p>###build_dynamic_target</p><ol><li>通过 select static_installer.pod_targets 筛选出 static_target，所过滤掉的是 target 是 spec 的第三方依赖。这里是过滤了 QueryKit ；</li><li>针对每个 subspec 生成相应的 <a href="https://rubydoc.info/gems/cocoapods/Pod/Sandbox/FileAccessor">FileAccessory</a> :</li><li>创建 PodTarget。</li></ol><h4>prepare_pods_project</h4><p>创建 Pod::Project，然后将 static project 中的 user configuration 复制过来，最后为 target 新建 Pods Group，这里的 group 是 <a href="https://www.rubydoc.info/gems/cocoapods/0.38.0/Pod/Project">PBXGroup</a> 。什么是 PBXGroup 呢？看下面的分组就明白的了：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*p1QnMWQdT2pUKVLf.jpg" /></figure><p>我们平时说看到的 Dependencies、Frameworks、Pods、Products、Target Support Files 他们在 CocoaPods 中都是对应了 PBXGroup。</p><h4>copy_dynamic_target</h4><p>从 static sandbox 中 cp 到 dynamic sandbox 目录下。</p><p><strong>install_file_references</strong></p><p>通过 <a href="https://www.rubydoc.info/gems/cocoapods/0.38.0/Pod/Installer/FileReferencesInstaller">FileReferencesInstaller</a> 为 dynamic target 生成文件引用，为最后的 project 写入做准备。FileReferencesInstaller 说明：</p><blockquote><em>Controller class responsible of installing the file references of the specifications in the Pods project.</em></blockquote><p><strong>install_library</strong></p><p>将 dynamic_target 写入新建的 project，同时会 install 依赖的 system framework。</p><h4>write_pod_project</h4><p>最后，将 project 写入 dynamic sandbox，修改 Search Path 保证能查询到依赖的 header 引用。</p><h3>Builder</h3><p>继 project 创建和 pod install 后，Package 中的 perform_build 先将所需参数传入以创建 Builder，开始执行 builder.build(@package_type) 。build 会依据 package_type 分为三种：</p><ul><li>build_static_library</li><li>build_static_framework</li><li>build_dynamic_framework</li></ul><p>这三个方法区别其实不大，就是 framework 的方法多了资源 copy 的过程。这里以 build_dynamic_framework 为例。</p><h4>build_dynamic_framework</h4><p>首先是先执行 compile 构建 Pods-packager ，成功后返回 defines。 <strong>compile</strong> 实现如下：</p><p>如果没有指定 --no-mangle 则正常执行 xcodebuild，否则转入 build_with_mangling 。</p><p>build_with_mangling 内部也是调用 xcodebuild，区别在于它生成的 defines 不同。mangling 会遍历 sandbox build 目录下的 libxxx.a 静态库来查找，核心方法如下：</p><p><a href="https://github.com/CocoaPods/cocoapods-packager/blob/master/lib/cocoapods-packager/mangle.rb">mangle.rb</a> 的描述如下：</p><blockquote><em>performs symbol aliasing，for each dependency:</em></blockquote><blockquote><em>​ — determine symbols for classes and global constants</em></blockquote><blockquote><em>​ — alias each symbol to Pod#{pod_name}_#{symbol}</em></blockquote><blockquote><em>​ — put defines into </em><em>GCC_PREPROCESSOR_DEFINITIONS for passing to Xcode</em></blockquote><p>mangling 也称为 namespacing，会把类名和全局常量改成 Pod#{pod_name}_#{symbol} 的形式。以我们调试的 KFData 的 PodsDummy_KFData 类为例：</p><p>就是统一在类前面添加了前缀，目的是为了避免静态库中的符号表冲突。比如，我们打包的 KFData 依赖了 QueryKit 那生成的 libKFData.a 静态库会有一份 QueryKit 的 copy，而此时如果在主工程里也直接引用了 QueryKit 那就会产生类似 duplicate symbols for architecture x86_64 的错误。</p><p>你可以 nm 工具来查看 class 的 symbol：</p><p>在查这个问题时，还填补了一个疑惑很久的问题： <a href="https://stackoverflow.com/questions/39160655/why-do-cocoapod-create-a-dummy-class-for-every-pod">Why do cocoapod create a dummy class for every pod?</a> CocoPods 上 <a href="https://github.com/CocoaPods/CocoaPods/issues/3410">issue_3410</a> 也有详细讨论</p><p><strong>build_sim_libraries</strong></p><p>由于 simulator 自由 iOS 有，实现比较简单，参数是前面 compile 返回的 defines。</p><p><strong>build_dynamic_framework_for_ios</strong></p><p>上面贴的代码看去很多，更多的是参数拼接的工作，主要做了三件事：</p><ul><li>xcodebuild 模拟器支持的 framework;</li><li>xcodebuild 真机支持的 framework;</li><li>lipo 合并👆生成的 framework 输出到 #{working_directory}/ios ;</li></ul><p>build_dynamic_framework_for_mac 省去 simulator build 这一步，也就没有 lipo 操作，更简单。这里就不列出了。</p><p>最后就是 resource、header、license 等相关资源的 copy。至此大致流程就结束了，用简单流程来回顾一下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xbH0PL6LkZQL1Pp6.jpg" /></figure><h3>总结</h3><p>cocoapods-packager 的逻辑还是比较简单的，整个熟悉过程困难还是在于对 CocoaPods 的 API 和作用并不是和了解，导致很多调用需要查资料或者看 CocoaPods 源码才能了大致理解。内部实现还是围绕 xcodebuild 来展开的，通过生成 podfile 及 pod install 来构建 project 环境，算是对 CocoaPods 的深度集成了。</p><p><em>Originally published at </em><a href="https://looseyi.github.io/post/sourcecode-ios/cocoapods-packager"><em>https://looseyi.github.io</em></a><em> on March 29, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6501ff5ae356" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[源码浅析 RxSwift 5.0 — Subscription]]></title>
            <link>https://medium.com/@liuedmond/%E6%BA%90%E7%A0%81%E6%B5%85%E6%9E%90-rxswift-5-0-subscription-6a752477f28c?source=rss-d3b3aa852ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a752477f28c</guid>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[source-code]]></category>
            <dc:creator><![CDATA[Liu Edmond]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 18:06:44 GMT</pubDate>
            <atom:updated>2020-03-27T18:06:44.597Z</atom:updated>
            <content:encoded><![CDATA[<h3>源码浅析 RxSwift 5.0 — Subscription</h3><h3>前言</h3><p>ReactiveX 它是一个与语言无关的编程思想。作为成员框架之一 RxSwift 落地了大部分 ReactiveX 中关于流的操作。官方描述：</p><blockquote><em>An API for asynchronous programming with observable streams</em></blockquote><blockquote><em>ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming</em></blockquote><p>本篇主要介绍 RxSwift 的内部流是如何产生和订阅，这里默认大家是有 RxSwift 使用经验的。关于响应式编程在移动端已经是一个相对成熟的概念了，有很多好文章，比如 <a href="https://halfrost.com/tag/rac/">FRP</a> 系列。如果你在项目中犹豫使用哪个框架可以看看这两篇文章的分析：</p><ul><li><a href="https://dreampiggy.com/2016/11/17/FRP%E7%AE%80%E4%BB%8B%E2%80%94ReactiveCocoa%E3%80%81RxSwift%E3%80%81Bacon%E4%BB%A5%E5%8F%8A%E8%83%8C%E5%90%8E%E7%9A%84Functional/">FRP对比 — ReactiveCocoa、RxSwift、Bacon以及背后的Functional</a></li><li><a href="https://www.jianshu.com/p/2f83b766a081">iOS响应式编程：ReactiveCocoa vs RxSwift 选谁好</a></li></ul><h3>Observable</h3><p>Rx 中的 Observable Stream(观察流)，为了方便这里简称为 <strong>流</strong>。流中的元数据可以有多个或者单个，这里统称为节点。既然一切皆流，那就从流的创建讲起，上代码：</p><pre>Observable.of(1, 2, 3)<br>    .subscribe( { print($0) })</pre><p>我们看第一行，它把 <strong>Swift.Sequence&lt;Int&gt;</strong> 序列 <em>[1, 2, 3]</em> 转换为流，<a href="https://github.com/ReactiveX/RxSwift/blob/c6c0c540109678b96639c25e9c0ebe4a6d7a69a9/RxSwift/Observables/Sequence.swift">of(_:)</a> 方法的声明如下：</p><pre>extension ObservableType {<br>   <br>    public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -&gt; Observable&lt;Element&gt; {<br>        return ObservableSequence(elements: elements, scheduler: scheduler)<br>    }<br>}</pre><p>利用 Swift 的 <a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#">Protcol Extesion</a> 来为 ObservableType 添加默认了实现，它把 Sequence&lt;Int&gt; 存入了 ObservableSequence 中并返回。</p><p>大概了解一下 ObservableSequence 的类关系：</p><pre>| --- ObservableSequence<br>    | --- Producer <br>        | --- Observable (class)<br>            | --- ObservableType (Protocol)<br>                | --- ObservableConvertibleType (Protocol)</pre><p>根协议 ObservableConvertibleType 利用关联类型声明了返回值为关联类型的泛型方法 asObservable:</p><pre>public protocol ObservableConvertibleType {<br>    /// Type of elements in sequence.<br>    associatedtype Element<br>    func asObservable() -&gt; Observable&lt;Element&gt;<br>}</pre><p>协议 ObservableType 则声明了 subscribe(_:) 方法：</p><pre>public protocol ObservableType: ObservableConvertibleType {<br>   <br>    func subscribe&lt;Observer: ObserverType&gt;(_ observer: Observer) -&gt; Disposable where Observer.Element == Element<br>}</pre><pre>extension ObservableType {<br>    /// Default implementation of converting `ObservableType` to `Observable`.<br>    public func asObservable() -&gt; Observable&lt;Element&gt; {<br>        // temporary workaround<br>        //return Observable.create(subscribe: self.subscribe)<br>        return Observable.create { o in<br>            return self.subscribe(o)<br>        }<br>    }<br>}</pre><p>并利用 subscribe(_:) 方法完成了对 asObservable() 默认实现的扩展。</p><p>关于注释 temporary workaround，翻了一下 <a href="https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/ObservableType.swift">git history</a> 在 Swift 3.0 添加的。这种写法在 Swift 5.0 上是可以 work 的，不知为何注释了。那为什么可以这么写呢 ？稍微扯一下，可以看 <a href="https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/Observables/Create.swift">creat(_:)</a> 的声明：</p><pre>extension ObservableType {<br>   <br>    public static func create(_ subscribe: @escaping (AnyObserver&lt;Element&gt;) -&gt; Disposable) -&gt; Observable&lt;Element&gt; {<br>        return AnonymousObservable(subscribe)<br>    }<br>}</pre><p>其参数 subscribe 是一个 closure，而 closure 本质就是匿名函数。在 Swift 中函数作为一等公民，是可以直接作为参数传递的。因此，上面可以省略 closure 直接写成：</p><pre>Observable.create(self.subscribe)</pre><p>再来 Observable ：</p><pre>public class Observable&lt;Element&gt; : ObservableType {<br>    <br>    public func subscribe&lt;Observer: ObserverType&gt;(_ observer: Observer) -&gt; Disposable where Observer.Element == Element {<br>        rxAbstractMethod()<br>    }<br>    <br>    public func asObservable() -&gt; Observable&lt;Element&gt; {<br>        return self<br>    }<br>}</pre><p>它仅做了两件事：</p><ol><li>将 subscribe(_:) 方法标记为抽象方法，并通过 <a href="https://swifter.tips/fatalerror/">fatalError</a> 来强制要求子类去实现；</li><li>在 asObservable() 中将 self 直接 return。</li></ol><p>上面代码中没有列出 init() 和 deinit() 的实现，RxSwift 在这两方法中引入了内部的资源统计，用于 debug，实现如下，感兴趣的可以深究:</p><pre>init() {<br>    #if TRACE_RESOURCES<br>        _ = Resources.incrementTotal()<br>    #endif<br>}<br>deinit {<br>    #if TRACE_RESOURCES<br>        _ = Resources.decrementTotal()<br>    #endif<br>}</pre><p>序列存储已经结束，流的创建才刚刚开始。先贴一张脑图补一补，其实每个流的变换操作背后都对应一个 ObservableType 的扩展。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGhym6RIVFD5AI-C" /></figure><h3><a href="https://github.com/ReactiveX/RxSwift/blob/c6c0c540109678b96639c25e9c0ebe4a6d7a69a9/RxSwift/Observables/Producer.swift">Producer</a></h3><p>再来看本文的重点之一 Producer：</p><pre>class Producer&lt;Element&gt; : Observable&lt;Element&gt; {<br>    override func subscribe&lt;Observer: ObserverType&gt;(_ observer: Observer) -&gt; Disposable where Observer.Element == Element {<br>        /// Scheduler {<br>        let disposer = SinkDisposer()<br>        let sinkAndSubscription = self.run(observer, cancel: disposer)<br>        disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)<br>        /// }<br>    }</pre><pre>    func run&lt;Observer: ObserverType&gt;(_ observer: Observer, cancel: Cancelable) -&gt; (sink: Disposable, subscription: Disposable) where Observer.Element == Element {<br>        rxAbstractMethod()<br>    }<br>}</pre><blockquote><em>注释的 Scheduler 是 RxSwift 中相关的线程调度，它会根据标识选择相应线程去处理任务，我们先忽略。</em></blockquote><p>看字面意思也能猜出它的作用吧。同样为抽象类，它的角色更像是一个管理者。它管理着 Observable 的创建、订阅、回收。每个 Producer 实例则对应一条流水线，而 RxSwift 则可以看作大型工厂，通过 Producer 持续的生产和消费 Observable。</p><h4>run(_:cancel:)</h4><p>它对应流的创建，也包括对每个节点发送 Event 事件。作为抽象方法，子类通过重载来提供流的多元化创建。同时 run 方法所返回的 sink 则保存了各个节点的元数据，subscription 则保存了流的订阅操作。详细会在 Sink 类作展开。</p><h4>subscribe(_:)</h4><p>它通过 sinkDisposer 来统一回收流所引用的元数据以及订阅相关的资源。</p><ol><li>判断是否需要用 scheduler 切换到指定的线程，来进行订阅逻辑的处理；</li><li>创建 sinkDisposer，同 obserer 一起作为 run(_:cancel:) 的入参；</li><li>将执行 run(_:cancel:) 方法后的结果保存到 sinkDisposer 中，为之后的资源销毁做准备；</li><li>最后返回 sinkDisposer；</li></ol><p>那就先就近先看 SinkDisposer 类。</p><h3>SinkDisposer</h3><blockquote><em>The returned disposable needs to release all references once it was disposed.</em></blockquote><p>SinkDisposer 用于保证所有引用资源的最终释放。其声明如下：</p><pre>private final class SinkDisposer: Cancelable {<br>    private enum DisposeState: Int32 {<br>        case disposed = 1<br>        case sinkAndSubscriptionSet = 2<br>    }</pre><pre>    private let _state = AtomicInt(0)<br>    private var _sink: Disposable?<br>    private var _subscription: Disposable?</pre><pre>    var isDisposed: Bool {<br>        return isFlagSet(self._state, DisposeState.disposed.rawValue)<br>    }</pre><pre>    func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { ... }</pre><pre>    func dispose() { ... }<br>}</pre><p>先分析它的继承关系：</p><pre>| --- SinkDisposer<br>    | --- Cancelable<br>        | --- Disposable</pre><p>Disposable 则是用于释放资源:</p><pre>public protocol Disposable {<br>    /// Dispose resource.<br>    func dispose()<br>}</pre><p>Cancelable，用于标识资源是否被释放：</p><pre>public protocol Cancelable : Disposable {<br>    /// Was resource disposed.<br>    var isDisposed: Bool { get }<br>}</pre><p>那 sinkDisposer 对保存结果做了什么处理，又是如何来释放资源的呢？主要靠下面这个方法。</p><h4><strong>setSinkAndSubscription</strong></h4><p>实现如下：</p><pre>self._sink = sink<br>self._subscription = subscription</pre><pre>let previousState = fetchOr(self._state, DisposeState.sinkAndSubscriptionSet.rawValue)<br>if (previousState &amp; DisposeState.sinkAndSubscriptionSet.rawValue) != 0 {<br>    rxFatalError(&quot;Sink and subscription were already set&quot;)<br>}</pre><pre>if (previousState &amp; DisposeState.disposed.rawValue) != 0 {<br>    sink.dispose()<br>    subscription.dispose()<br>    self._sink = nil<br>    self._subscription = nil<br>}</pre><ol><li>保存 sink 和 subscription （均为 Disposable）</li><li>获取 previousState （当前资源的状态是否被标示为已清理或已设置) ；</li><li>如果 previousState 为 .sinkAndSubscriptionSet，则已设置过资源，直接抛错来防止重复调用；</li><li>如果 previousState 为 .disposed，则资源已不可用，会对 sink 和 subscription 执行 dispose() 以释放资源，同时将它们置 nil。</li></ol><p>这里，可能有小伙伴有疑问，一个 state 如何保存两个状态？来瞅一眼 <a href="https://github.com/ReactiveX/RxSwift/blob/master/Platform/AtomicInt.swift">AtomicInt</a> 简化后的部分实现：</p><pre>final class AtomicInt: NSLock {<br>    fileprivate var value: Int32<br>    public init(_ value: Int32 = 0) {<br>        self.value = value<br>    }<br>}</pre><pre>func fetchOr(_ this: AtomicInt, _ mask: Int32) -&gt; Int32 {<br>    this.lock()<br>    let oldValue = this.value<br>    this.value |= mask<br>    this.unlock()<br>    return oldValue<br>}</pre><pre>func increment(_ this: AtomicInt) -&gt; Int32 {<br>    return add(this, 1)<br>}</pre><pre>func decrement(_ this: AtomicInt) -&gt; Int32 {<br>    return sub(this, 1)<br>}</pre><pre>...</pre><blockquote><em>说明：Atomic 中有返回值都的方法都有 </em><strong><em>@discardableResult</em></strong><em> 标记，只是这边简化了，同时所有方法都是 </em><strong><em>@inline(__always)</em></strong><em> 标记的。</em></blockquote><p>之前版本的 AtomicInt 是用 <a href="https://opensource.apple.com/source/xnu/xnu-201.5/libkern/libkern/OSAtomic.h.auto.html">OSAtomic.h</a> 的 API 来实现的，现在改成用 NSLock 了。</p><p>这里看到 <em>位运算符</em> 大家应该知道它是怎么实现了吧。它通过每个 bit 来保存一个 flag 从而提高了访问效率。</p><p>接着我们看 fetchOr(_:_:) 它其实做了两件事情。</p><ol><li>先取出当前 value 做为返回值；</li><li>将 mask 值保存到 value 中；</li></ol><p>by the way，前面提到过 RxSwift 内部的资源统计方法 Resources.incrementTotal() 就是用 increment(_:) 实现的。 Resources.decrementTotal() 同理。</p><h4>dispose</h4><p>理解了 setSinkAndSubscription 后 dispose 就不难了，实现如下：</p><pre>let previousState = fetchOr(self._state, DisposeState.disposed.rawValue)</pre><pre>if (previousState &amp; DisposeState.disposed.rawValue) != 0 {<br>    return<br>}</pre><pre>if (previousState &amp; DisposeState.sinkAndSubscriptionSet.rawValue) != 0 {<br>    guard let sink = self._sink else {<br>        rxFatalError(&quot;Sink not set&quot;)<br>    }<br>    guard let subscription = self._subscription else {<br>        rxFatalError(&quot;Subscription not set&quot;)<br>    }</pre><pre>    sink.dispose()<br>    subscription.dispose()</pre><pre>    self._sink = nil<br>    self._subscription = nil<br>}</pre><ol><li>先取出 previousState 并将 .disposed 值写入 _state;</li><li>判断 previousState 为 disposed：</li><li>如果是则表明已经清理过，直接 return；</li><li>否则对 sink 和 subscription 执行 dispose() 以释放资源，同时将它们置 nil。</li></ol><p>RxSwift 通过 AutomicInt 的位运算，巧妙的用一个变量高效完成了多个状态的存储，最重要的是它保证了只有一次有效的 dispose 操作。还有很重要的一点，在释放资源后，sinkDisposer 都会主动将 sink 和 subscription 置 nil，这是为了解决<strong>循环引用</strong>。因为在 Sink 内部其实也引用了 sinkDisposer。</p><h3>Sink</h3><p>项目中的 issue 有一个简单描述 <a href="https://github.com/ReactiveX/RxSwift/issues/817">What is a Sink ?</a></p><blockquote><em>It’s an internal class used to implement the operators, that receives events and processes them.</em></blockquote><p>Sink，接受 Event 事件并进行相应处理或者将其转发，是实现各种运算符的内部类，比如 Map、Reduce、Filter 运算符等。作为 Producer 背后的苦力一直默默付出。</p><p>Sink 从哪里来的呢？继续以开头的 Observable.of(1, 2, 3) 为例，看 ObservableSequence 的 run 方法实现：</p><pre>final private class ObservableSequence&lt;Sequence: Swift.Sequence&gt;: Producer&lt;Sequence.Element&gt; {<br>    /// init ...<br>   <br>    override func run&lt;Observer: ObserverType&gt;(_ observer: Observer, cancel: Cancelable) -&gt; (sink: Disposable, subscription: Disposable) where Observer.Element == Element {<br>        let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel)<br>        let subscription = sink.run()<br>        return (sink: sink, subscription: subscription)<br>    }<br>}<br>复制代码</pre><p>在其初始化时将关键数据都保存起来：</p><ul><li>self 为 Swift.Sequence&lt;Int&gt;</li><li>observer</li><li>cancel 为 SinkDisposer</li></ul><p>Sink 创建完后会将执行 run() 的结果作为 subscription，同 sink 一起返回后存入 sinkDisposer 中。这也是前面提到的有循环引用的情况，不过在 sinkDispoer 的 dispose 过程中做了 break。</p><p>Sink 声明如下：</p><pre>class Sink&lt;Observer: ObserverType&gt; : Disposable {<br>    fileprivate let _observer: Observer<br>    fileprivate let _cancel: Cancelable // sinkDisposer<br>    private let _disposed = AtomicInt(0)</pre><pre>    final func forwardOn(_ event: Event&lt;Observer.Element&gt;) {<br>        if isFlagSet(self._disposed, 1) {<br>            return<br>        }<br>        self._observer.on(event)<br>    }</pre><pre>    final func forwarder() -&gt; SinkForward&lt;Observer&gt; {<br>        return SinkForward(forward: self)<br>    }</pre><pre>    final var disposed: Bool {<br>        return isFlagSet(self._disposed, 1)<br>    }</pre><pre>    func dispose() {<br>        fetchOr(self._disposed, 1)<br>        self._cancel.dispose()<br>    }<br>}</pre><p>又见到 AtomicInt，这次是修饰 _disposed 属性，各位自行理解。我们看核心方法：</p><ol><li>forwardOn(_:) 用于转发，将 event 事件传递到 Observer.on(_:)；</li><li>dispose() 直接调用 sinkDisposer -&gt; dispose();</li></ol><p>forwarder() 返回的 SinkForward 是 Observer 对象，它将 sink 的 observer 做了包装，该方法主要用于 timeout() 方法。转发逻辑如下：</p><pre>final class SinkForward&lt;Observer: ObserverType&gt;: ObserverType {</pre><pre>    final func on(_ event: Event&lt;Element&gt;) {<br>        switch event {<br>        case .next:<br>            self._forward._observer.on(event)<br>        case .error, .completed:<br>            self._forward._observer.on(event)<br>            self._forward._cancel.dispose()<br>        }<br>    }<br>}</pre><p>它不仅收集资源同时还加工以及转发事件。最后回到 ObservableSequenceSink 来看 run() 方法：</p><pre>final private class ObservableSequenceSink&lt;Sequence: Swift.Sequence, Observer: ObserverType&gt;: Sink&lt;Observer&gt; where Sequence.Element == Observer.Element {<br>    typealias Parent = ObservableSequence&lt;Sequence&gt;</pre><pre>    private let _parent: Parent</pre><pre>    func run() -&gt; Disposable {<br>        return self._parent._scheduler.scheduleRecursive(self._parent._elements.makeIterator()) { iterator, recurse in<br>            var mutableIterator = iterator<br>            if let next = mutableIterator.next() {<br>                self.forwardOn(.next(next))<br>                recurse(mutableIterator)<br>            }<br>            else {<br>                self.forwardOn(.completed)<br>                self.dispose()<br>            }<br>        }<br>    }<br>}</pre><p><strong>_scheduler.scheduleRecursive</strong> 背后是 RxSwift 对于容器对象的线程调度，也不展开。这里的 run()方法 做了几个事情：</p><ol><li>Scheduler 会在指定线程中调用 Swift.Sequence 的迭代器，以遍历每个元素。</li><li>获取到元素后，将 next 事件不断转发给 Observer；</li><li>迭代结束后，发送 completed 事件至 Observer 并调用 dispose 出发 sinkDisposer 的资源清理操作；</li></ol><p>关于 Sink 再说明一下，本篇是以 Sequence 作为切入点，不同 Operator 背后的 Producer 所产生的 Sink 实现是有不少区别的，比如 Just 流只产生单个节点，则直接在重载的 subscribe 方法里发送 Event 然后就调用 dispose 结束了。因此，每个 operator 的实现会有比较大的出路，但是整体流程是由这些内部类来限制和保证的。</p><h3>Subscription</h3><p>我们回到文章开头接着聊一聊订阅：</p><pre>.subscribe( { print($0) })</pre><p>同 of(_:) 一样，订阅也是对 <a href="https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/ObservableType%2BExtensions.swift">ObservableType 扩展</a>来实现的。简化后如下：</p><pre>extension ObservableType {</pre><pre>    public func subscribe(_ on: @escaping (Event&lt;Element&gt;) -&gt; Void)<br>        -&gt; Disposable {<br>            let observer = AnonymousObserver { e in<br>                on(e)<br>            }<br>            return self.asObservable().subscribe(observer)<br>    }</pre><pre>    public func subscribe(onNext: ((Element) -&gt; Void)? = nil, onError: ((Swift.Error) -&gt; Void)? = nil, onCompleted: (() -&gt; Void)? = nil, onDisposed: (() -&gt; Void)? = nil)<br>        -&gt; Disposable {<br>        ...<br>    }<br>}</pre><p>两个 subscribe 方法都是将订阅的操作存入 AnonymousObserver 中，然后通过 asObservable() 获取 producer 并最终其 subscribe(_:) 以完成订阅。</p><p>我们看看 <a href="https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/Observers/AnonymousObserver.swift">AnonymousObserver</a> 是什么来头：</p><pre>final class AnonymousObserver&lt;Element&gt;: ObserverBase&lt;Element&gt; {<br>    typealias EventHandler = (Event&lt;Element&gt;) -&gt; Void<br>    <br>    private let _eventHandler : EventHandler<br>    /// 这里同样忽略了 `init()` 与 `deinit()` 的资源统计逻辑<br>    init(_ eventHandler: @escaping EventHandler) {<br>        /// 资源统计<br>        self._eventHandler = eventHandler<br>    }</pre><pre>    override func onCore(_ event: Event&lt;Element&gt;) {<br>        return self._eventHandler(event)<br>    }<br>}</pre><p>很简单，仅有一个 _eventHandler 属性保存订阅操作，然后在 onCore(_:) 中调用它。在翻它父类之前，看一眼它的继承关系：</p><pre>| --- AnonymousObserver<br>    | --- ObserverBase<br>        | --- Disposable、ObserverType</pre><p>Disposable 我们已经知道了，看 ObserverType：</p><pre>public protocol ObserverType {<br>    associatedtype Element</pre><pre>    func on(_ event: Event&lt;Element&gt;)<br>}</pre><pre>/// Convenience API extensions to provide alternate next, error, completed events<br>extension ObserverType {</pre><pre>    public func onNext(_ element: Element) {<br>        self.on(.next(element))<br>    }</pre><pre>    public func onCompleted() {<br>        self.on(.completed)<br>    }<br>    <br>    public func onError(_ error: Swift.Error) {<br>        self.on(.error(error))<br>    }<br>}</pre><p>声明了 on(_:) 方法，同时针对 Event 的类型提供了三个便利方法。Event 则是一个嵌套枚举类型：</p><pre>public enum Event&lt;Element&gt; {<br>    /// Next element is produced.<br>    case next(Element)</pre><pre>    /// Sequence terminated with an error.<br>    case error(Swift.Error)</pre><pre>    /// Sequence completed successfully.<br>    case completed<br>}</pre><h4>ObserverBase</h4><p>我们来看 <a href="https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/Observers/ObserverBase.swift">ObserverBase</a>：</p><pre>class ObserverBase&lt;Element&gt; : Disposable, ObserverType {<br>    private let _isStopped = AtomicInt(0)</pre><pre>    func on(_ event: Event&lt;Element&gt;) {<br>        switch event {<br>        case .next:<br>            if load(self._isStopped) == 0 {<br>                self.onCore(event)<br>            }<br>        case .error, .completed:<br>            if fetchOr(self._isStopped, 1) == 0 {<br>                self.onCore(event)<br>            }<br>        }<br>    }</pre><pre>    func onCore(_ event: Event&lt;Element&gt;) {<br>        rxAbstractMethod()<br>    }</pre><pre>    func dispose() {<br>        fetchOr(self._isStopped, 1)<br>    }<br>}</pre><p>ObserverBase 利用 Atomic 声明的 _isStopped 属性作为哨兵，以保证资源被标记 _isStopped 后不会产生重复调用的。那么，如何做到的呢？</p><p>通过判断 _isStopped 是否为 0 来表示资源是否可用。一旦调用 dispose() 会将其值置为 1，则资源不可用。另一种情况则在 on 方法内，实现逻辑如下：</p><ol><li>event 为 .next 事件：通过 load(_:) 取出 _isStopped 值并判断值是否为 0，是则执行 onCore(event) ；</li><li>event 为 .error、.completed 事件：</li><li>通过 fetchOr(_:) 取出 _isStopped 当前值后并将其置为 1，以保证不再重入；</li><li>判断 _isStopped 当前值是否为 0，是则执行 onCore(event) 。</li></ol><p>因此 ObserverBase 核心功作用是保证暴露给子类的 onCore(_:) 在观察结束后不会被重复执行。也就是保证 AnonymousObserver 的 eventHandler 被正确执行。</p><p>最后，回顾一下订阅相关流程：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UoaapjZU4tsh54i1" /></figure><h3>总结</h3><p>RxSwift 所展示的订阅流的处理，不仅充分利用了 Swift 语言本身的特性，如为协议添加默认实现、采用泛型来约束类的行为、天然支持链式调用等。通过经典的设计模式 <a href="https://www.wikiwand.com/en/Producer%E2%80%93consumer_problem">Producer–consumer</a>，以多元化的 Producer 来轻松支持各种 operator 的实现。还有就是巧妙的运用了位运算来简化逻辑。</p><p>由于篇幅有限，Schedule 的调度逻辑并未展开，还有就是 DisposeBag 通篇未提及，就当是思考作业啦。</p><p>About Me：土土Edmond木<br>Github：<a href="https://looseyi.github.io/">https://looseyi.github.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a752477f28c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[完善 Cocoapods-Binary 支持 Server 端缓存]]></title>
            <link>https://medium.com/@liuedmond/%E5%AE%8C%E5%96%84-cocoapods-binary-%E6%94%AF%E6%8C%81-server-%E7%AB%AF%E7%BC%93%E5%AD%98-7aa8382ae540?source=rss-d3b3aa852ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aa8382ae540</guid>
            <category><![CDATA[cocoapods-package]]></category>
            <category><![CDATA[二进制化]]></category>
            <category><![CDATA[ios-binary]]></category>
            <category><![CDATA[cocoapods]]></category>
            <dc:creator><![CDATA[Liu Edmond]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 16:44:51 GMT</pubDate>
            <atom:updated>2020-01-05T16:44:51.426Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>在开始之前，还是明确一下我们的目标，希望通过对 Cocoapods-binary 的改造使其支持 server 端缓存，从而达到 一处编译，处处使用 的 pods lib dependencies。同时会简单对比一下现有已经公开的大厂的实践和利弊，以及我们为何这么做。</blockquote><h3>业内实践</h3><p>对于人数较多的业务团队，为了更好的团队协作组件化是不可避免的，关于如何逐步的组件拆分以及提升编译美团有一篇不错的入门 <a href="https://tech.meituan.com/2018/06/29/ios-multiterminal-reuse.html"><em>美团外卖iOS多端复用的推动、支撑与思考</em></a><em> </em>里面提到了项目的二进制化，但是并没有涉及如何实现的，更多是关于如何分步进行组件化迭代。那么如何开始，又有哪些巨人的肩膀可以踩呢？</p><p><a href="https://zhuanlan.zhihu.com/p/44280283"><strong>知乎 iOS 基于 CocoaPods 实现的二进制化方案</strong></a></p><p>知乎的实践是基于项目工程在提交 PR 后触发 binary package 的 CI 脚本，相对完整描述了如何进行源码和 binary 的切换和控制，生成的 binary package 如何在 server 端存储，还附了基本的流程图。总结一下要点：</p><ul><li>通过 YML 配置 binary 白名单、文件服务配置信息等；</li><li>利用libo将xcodebuild后的 dSYM 和 binary 整合（包含了模拟器和真机设备）后的 ZIP 包上传至静态服务器，得到对应的 URL；</li><li>利用 CocoaPods Analysis 修改 podSpec 将 binary 为true的库的 source 指向获取到的 URL，同时更新 Tag。将修改后的 spec 文件推送至私有仓库；</li></ul><p><strong>分析</strong></p><ol><li>通过 YML 配置来控制源码和 binary 切换是不错的方式，不过如果能基于cocoapod-plugin 插件给 pod DSL 添加 binary 的属性来控制就更好了。</li><li>对于修改 podspec 以及更新 Private Pod Repo 感觉是有一点冗余的。其实可以在 install 过程中检查 binary 为 true 的 pod 是否已有打好的 ZIP 包，存在则替换，否则进入 prebuild 流程打包即可。当然这里需要约定好生成的 ZIP 包名，知乎是以 tag + zhihu-static，如/path/to/server/AFNetworking-3.20-zhihu-static。本质上不论使用哪种方式引用 Pod，背后对应的都是 spec 文件里配置的 source 所指向仓库中对应的一个Git 节点（PS：每个 commit 对应的 hash，所以管理好版本很重要）。CocoaPods 在解决冲突依赖时，是依据<a href="https://semver.org/"><em>语义化版本</em></a>来递归，所以我认为是不需要单独对应的 static spec。</li></ol><p><a href="https://www.infoq.cn/article/hIUoAJjKNS3_TVdaf0EG"><strong>火掌柜 iOS 端基于 CocoaPods 的组件二进制化实践</strong></a></p><p>同样采用双私有源策略，一个静态服务器保存预先打好包的 binary，一个是源码服务地址。区别于知乎的方案的地方是，他们事先将各个私有库更新时，触发 CI 打包并上传服务器，在 pod install 过程中进行替换源。知乎是在完整项目的构建中完成对 binary 的打包和替换，知乎这样的一揽子方案才是正解。不过该文章提到不少在实践中的坑，有比较多的参考意义，他们还产出了一个 Pod 插件 <a href="https://github.com/tripleCC/cocoapods-bin/"><em>CocoaPods-bin</em></a><em>。</em>总结一下该文章要点：</p><ul><li>改造 CocoaPods-Package ，支持对单个 pod 进行二进制编译，打包上传静态服务器;</li><li>基于 Podfile 中添加的全局变量 tdfire_use_source_pods 来控制 binary 白名单，pod install 时注入环境变量以控制源码切换；</li></ul><p><strong>分析</strong></p><ol><li>CocoaPods-Package 作为官方提供的插件在 1.7.0 正式版发布后做了一次更新，也是时隔多年，支持了Swift 的 package 及修复了一些问题。以单个 pod 进行二进制编译的最大麻烦在于，团队如果进行了比较重度的组件化，一般会有大量依赖库需要维护，如果每个库都需要配置一份 package 脚本成本比较高，同时第三方库也需要进行镜像维护，尽管支持了 CI 自动化也需要花费一部分精力，同时业务工程师也需要对项目有完整的认知，否则难以捋清其中的关系。</li><li><em>以 </em><em>IS_SOURCE</em>环境变量控制 binary 和源码切换的方式也不是很友好。也是可以给 pod DSL 添加扩展来支持 binary switch。当前在每次 install 前加入变量去控制，使用上感觉有些奇怪；</li></ol><h3>改造 CocoaPods-Binary</h3><p>关于 Cocoapods-Binary 前段时间写过一篇简单介绍，<a href="https://medium.com/@liuedmond/%E6%B5%85%E6%9E%90-cocoapods-binary-%E5%AE%9E%E7%8E%B0-1a8ab2fef4df"><em>浅析 Cocoapods-Binary 实现</em></a><em>。</em>在了解了该插件如何工作之后，就可以将我们端想法付诸实践了。</p><p>首先，我们要做的事情很多插件都已经帮我们完成了，而我们要做的就是简单的支持一下对 binary framework 的静态服务器存储和下发就好，先来一张流程图：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlVys8B6WC_Gz74pJHGOmw.png" /><figcaption>cocoapods-binary 改造</figcaption></figure><p>上图中的 featch remote framework 和 upload zips to server 就是我们要做的事情。</p><ul><li>在 Prebuild framework 之前检查当前 pod_target 是否有对应的 server cache，存在则 download 至本地同时 unarchive 至 GenerateFramework 文件目录下，然后跳过当前 pod_target 的编译。下面代码对应链接为 gist 代码片段。<a href="https://gist.github.com/looseyi/97820689ff80aa58c9791ece45d22a96"><em>exist_remote_framewo = sandbox.fetch_remote_framework_for_target(target)</em></a></li><li>在 Prebuild 结束后会进行文件清理和 binary 的替换链接，在此时进行批量 binary 文件的同步。将GenerateFramework 目录中所匹配的 pod_target 且资源服务器所不存在的 binary 文件进行上传，统一至 static_frameworks 目录下，文件名则是 pod_name + tag, 例如 pod &#39;AFNetworking&#39;, &#39;3.0&#39;对应的 zip framework 名字为 AFNeworkings-3.0.0.zip 。对应 gist 代码为：<a href="https://gist.github.com/looseyi/f5674ad527c1a7e6d5cf896cfb4f0237"><em>sync_prebuild_framework_to_server(target)</em></a></li></ul><p>实践过程中，为了方便直接是利用了公司现有的 ftp 文件服务器，单独开了一个进行目录维护。相比 CocoaPods-binary 仅增加了 ftp_tools.rb 和 zip_tools.rb 两个文件，实现比较简单这里就不贴出来了。</p><h3>限制</h3><ul><li>最终的 binary size 会比使用源码的时候大一点，不建议最终上传 Store 的时候使用；</li><li>缺少一个验证的机制，如果已发布的二进制包不能被项目正常引用，那么会导致所有人的编译失败；；</li><li>由于工程采用的是全部静态库依赖的形式，所以在二进制和源码切换的过程中会对 project 文件产生更改；</li><li>CocoaPods 在 1.7 以上版本，更改了framework 逻辑，不会把 resource copy 至 framework，因此我们需要将 CocoaPods 版本固定到 1.6.x；</li><li>对于动态配置生成的 framework，例如RN 相关的依赖等，不支持binary；</li><li>不同版本 Swift 编译出的 binary 是不能兼容。如果项目中引用了 Swift 库Xcode 版本需要统一。</li></ul><p>在使用 binary 的过程中，还有一些意想不到的问题。例如，为了减少源码和 binary 切换过程中产生的大量 git change，将 Pods 目录进行了 ignore，导致工程师在过渡阶段切换分支中，多数被限制在 pod install 中一些三方库的 download 上面，非翻所不能也。还有，在 install 后发现 pod 对应的 symbol link 没有正确生成、对应的 source 没有 copy 成功、业务 framework 打包耗时超常等一系列问题。</p><h3>总结</h3><p>真实项目实践中，没有一劳永逸的办法。不同的业务依赖和环境配置，包括工程代码的规范，甚至简单的头文件管理都会导致开发过程产生各种各样的问题。总之，是一个不断探索和进化的过程。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aa8382ae540" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[浅析 Cocoapods-Binary 实现]]></title>
            <link>https://medium.com/@liuedmond/%E6%B5%85%E6%9E%90-cocoapods-binary-%E5%AE%9E%E7%8E%B0-1a8ab2fef4df?source=rss-d3b3aa852ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8ab2fef4df</guid>
            <category><![CDATA[ios-binary]]></category>
            <category><![CDATA[cocoapods]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[prebuild]]></category>
            <dc:creator><![CDATA[Liu Edmond]]></dc:creator>
            <pubDate>Sat, 21 Dec 2019 10:54:28 GMT</pubDate>
            <atom:updated>2019-12-21T10:54:28.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>背景</h3><p>公司级别的项目在发展过程，不可避免会遇到项目过大，导致的编译和开发效率的降低。在如何提高编译速度，加快生产效率，各大厂都有各种尝试，可惜在业内没有一个成本低、效果好的开源方案。而作者所在的公司，由于业务线聚合，原有两条完全不同的交易线业务以组件的形式合并到主App，加剧了编译的问题。项目的完整编译时间从原有的5分钟，直接 double 到25分钟左右，同时 CI 的打包也不断的往30分钟的趋势奔去。</p><h3>思路</h3><p>CocoaPods-Binar 是针对二进制化的一个整体的实践，而非像 CocoaPods-Packager 仅仅针对单个私有库的。所谓的二进制化，简单说来可以通过 podSpec 将 source 指向事先打包好的 binary 来提高编译效率，这个是目前的主流做法。当然也可以通过更改编译缓存如 CCache 或者换个编译器 Buck (FB) / Bazel (Google) 来实现分布式编译。微信团队的这篇 <a href="https://mp.weixin.qq.com/s/-wgBhE11xEXDS7Hqgq3FjA"><em>微信编译速度优</em>化</a> 有进行了比较完整的阐述。而本文的主角 CocoaPods-Binary 是通过将 dependencies 预编译成 binary 后缓存至本地，然后将原有的 Source Code link 到 binary 以几乎零成本的方式实现编译效率的提高。唯一缺点就是无法实现服务端缓存（这是我们需要改造的地方，不过这个可以通过定制化实现)，所谓的<em>分布式的二进制编译。</em></p><h3>CocoaPod-Binary</h3><p>最早发现这个 plugin 是在浏览官方 <a href="https://guides.cocoapods.org/plugins/pre-compiling-dependencies.html">blog</a> 时发现的，而且作者还是国内 developer 。该插件发布也有两年多，目前支持到 Pods 版本 1.6.x。我们先来看看类图构成：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfTYqkbJKCT_rlTmO3rZ_A.png" /></figure><p>CocoaPods 本身提供了比较不错的插件模版，如需要的话可以看<a href="https://medium.com/@vladkorzun/getting-started-with-cocoapods-plugin-development-86cd55bee1b3">这篇</a>文章。CocoaPods-Binary 的核心代码都在 <a href="https://github.com/leavez/cocoapods-binary/tree/master/lib">lib</a>/cocoapods-binary 文件夹下。我们来看看整个插件的主要部件，及其对应的作用。</p><p><strong>Main</strong></p><p>作为整个插件的执行的入口，通过 CocoaPods 提供的 pre_install hook 在 pod install 的 prepare 阶段拦截到当前的 pod install context，进而 fork 出一份独立的 installer 以完成将预编译源码 clone 至 Pod/_Prebuild 目录下。</p><p><strong>Helper</strong></p><p>主要对 Sandbox、Installer、Pod、Podfile Options 相关的类添加各种 attribute 状态来满足逻辑需要。例如，子类化 Sandbox &gt; PrebuildSandbox 来指定 generate frameworks 的地址、prebuild Pods 的地址，以及是否存在编译好的 framework 等；对 Podfile DSL 添加 <em>binary、all_bianry </em>关键字来控制 binary 和源码的切换。</p><p><strong>Room Build Framework</strong></p><p>核心类，通过 xcodebuild 将所有<em> :binary =&gt; true </em>的 dependencies 编译成 binary 和 dSYM，并输出到指定目录。这里针对 iOS 平台输出的 framework 多做了一步处理，当检测到是 platform 是 iOS 会分别对模拟器和真机设备单独编译，最后再利用 <em>libo </em>将各自的 binary 和 dSYM 合并成一份输出。</p><p><strong>Prebuild Installer</strong></p><p>利用 ruby 语言的动态性，重载 Installer 的 <em>run_plugins_post_install_hooks</em> 以实现 pre_install 结束后触发 build framework 将 dependencies 打包成二进制包。对于 dependencies 是否需要进行预编译是通过检查生成的 framework 中是否存在 xxx_name 文件作为标识该 lib 是否已经完成编译过（xxx 为对应 lib 名称。</p><p><strong>Integration</strong></p><p>在插件源码同步完预编译结束后，会将 install context 交还，进入 install 最后阶段。在这里将完成对 binary frameworks 的 symbol link 以替换原有 Pods 源码和 Embed 操作则会修改各个 pod.xcproject 配置，最后生成 project。</p><h3>结果</h3><p>基本的模块介绍完，我们来看看，引入 CocoaPods-Binary 插件后 Pods 的文件构成：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d520uYozTSqzeRH-B4bYdQ.png" /></figure><p>_Prebuild 目录下则完整保存了一份 Pods 源代码，同时多出来的 GeneratedFrameworks 则缓存了预编译后的 binary 文件以及 dSYM 符号表。在最后的 integration 阶段 symbol link 替换完后源码则会被删除同时指向binary。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*0JSr_bZbGJvYyjFYGzHogQ.png" /></figure><p>至此，整个 pod install 就算完成了，那 CocoaPods有哪些限制呢？</p><ul><li>于 CocoaPods 在 1.7.x 以上版本，修改了 framework 生成逻辑，不会把 bundle copy 至 framework，因此我们需要将 Pod 环境固定到 1.6.2；</li><li>pod 要支持 binary，header ref 需要变更为 #import &lt;&gt;或者 @import 以符合 moduler 标准；</li><li>统一 CI 和开发的 compiler 环境，如果项目支持 Swift，不同 compiler 编译产物有 Swift 版本兼容问题；</li><li>最终的 binary size 会比使用源码的时候大一点，不建议最终上传 Store；</li><li>建议 Git ignore Pods 文件夹，否则在 source code 与 binary 切换过程会有大量的 file change，增加 git 负担；</li></ul><h3>流程图</h3><p>无图无真相，简单的流程图希望能帮助各位理解 CocoaPods-Binary 作者的基本思路；</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlVys8B6WC_Gz74pJHGOmw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8ab2fef4df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>