陈文艺 6 months ago
commit
bf03499acf
100 changed files with 21161 additions and 0 deletions
  1. 22 0
      LICENSE
  2. 187 0
      README.md
  3. 145 0
      Vendor/WebP.framework/Headers/config.h
  4. 488 0
      Vendor/WebP.framework/Headers/decode.h
  5. 358 0
      Vendor/WebP.framework/Headers/demux.h
  6. 527 0
      Vendor/WebP.framework/Headers/encode.h
  7. 51 0
      Vendor/WebP.framework/Headers/extras.h
  8. 88 0
      Vendor/WebP.framework/Headers/format_constants.h
  9. 530 0
      Vendor/WebP.framework/Headers/mux.h
  10. 97 0
      Vendor/WebP.framework/Headers/mux_types.h
  11. 52 0
      Vendor/WebP.framework/Headers/types.h
  12. BIN
      Vendor/WebP.framework/WebP
  13. 196 0
      YYKit/Base/Foundation/NSArray+YYAdd.h
  14. 172 0
      YYKit/Base/Foundation/NSArray+YYAdd.m
  15. 92 0
      YYKit/Base/Foundation/NSBundle+YYAdd.h
  16. 87 0
      YYKit/Base/Foundation/NSBundle+YYAdd.m
  17. 310 0
      YYKit/Base/Foundation/NSData+YYAdd.h
  18. 642 0
      YYKit/Base/Foundation/NSData+YYAdd.m
  19. 188 0
      YYKit/Base/Foundation/NSDate+YYAdd.h
  20. 188 0
      YYKit/Base/Foundation/NSDate+YYAdd.m
  21. 197 0
      YYKit/Base/Foundation/NSDictionary+YYAdd.h
  22. 392 0
      YYKit/Base/Foundation/NSDictionary+YYAdd.m
  23. 45 0
      YYKit/Base/Foundation/NSKeyedUnarchiver+YYAdd.h
  24. 51 0
      YYKit/Base/Foundation/NSKeyedUnarchiver+YYAdd.m
  25. 97 0
      YYKit/Base/Foundation/NSNotificationCenter+YYAdd.h
  26. 62 0
      YYKit/Base/Foundation/NSNotificationCenter+YYAdd.m
  27. 33 0
      YYKit/Base/Foundation/NSNumber+YYAdd.h
  28. 63 0
      YYKit/Base/Foundation/NSNumber+YYAdd.m
  29. 302 0
      YYKit/Base/Foundation/NSObject+YYAdd.h
  30. 396 0
      YYKit/Base/Foundation/NSObject+YYAdd.m
  31. 31 0
      YYKit/Base/Foundation/NSObject+YYAddForARC.h
  32. 40 0
      YYKit/Base/Foundation/NSObject+YYAddForARC.m
  33. 53 0
      YYKit/Base/Foundation/NSObject+YYAddForKVO.h
  34. 110 0
      YYKit/Base/Foundation/NSObject+YYAddForKVO.m
  35. 409 0
      YYKit/Base/Foundation/NSString+YYAdd.h
  36. 414 0
      YYKit/Base/Foundation/NSString+YYAdd.m
  37. 25 0
      YYKit/Base/Foundation/NSThread+YYAdd.h
  38. 107 0
      YYKit/Base/Foundation/NSThread+YYAdd.m
  39. 66 0
      YYKit/Base/Foundation/NSTimer+YYAdd.h
  40. 35 0
      YYKit/Base/Foundation/NSTimer+YYAdd.m
  41. 97 0
      YYKit/Base/Quartz/CALayer+YYAdd.h
  42. 324 0
      YYKit/Base/Quartz/CALayer+YYAdd.m
  43. 338 0
      YYKit/Base/Quartz/YYCGUtilities.h
  44. 271 0
      YYKit/Base/Quartz/YYCGUtilities.m
  45. 89 0
      YYKit/Base/UIKit/UIApplication+YYAdd.h
  46. 239 0
      YYKit/Base/UIKit/UIApplication+YYAdd.m
  47. 32 0
      YYKit/Base/UIKit/UIBarButtonItem+YYAdd.h
  48. 62 0
      YYKit/Base/UIKit/UIBarButtonItem+YYAdd.m
  49. 37 0
      YYKit/Base/UIKit/UIBezierPath+YYAdd.h
  50. 64 0
      YYKit/Base/UIKit/UIBezierPath+YYAdd.m
  51. 358 0
      YYKit/Base/UIKit/UIColor+YYAdd.h
  52. 474 0
      YYKit/Base/UIKit/UIColor+YYAdd.m
  53. 78 0
      YYKit/Base/UIKit/UIControl+YYAdd.h
  54. 118 0
      YYKit/Base/UIKit/UIControl+YYAdd.m
  55. 193 0
      YYKit/Base/UIKit/UIDevice+YYAdd.h
  56. 515 0
      YYKit/Base/UIKit/UIDevice+YYAdd.m
  57. 153 0
      YYKit/Base/UIKit/UIFont+YYAdd.h
  58. 269 0
      YYKit/Base/UIKit/UIFont+YYAdd.m
  59. 47 0
      YYKit/Base/UIKit/UIGestureRecognizer+YYAdd.h
  60. 78 0
      YYKit/Base/UIKit/UIGestureRecognizer+YYAdd.m
  61. 377 0
      YYKit/Base/UIKit/UIImage+YYAdd.h
  62. 752 0
      YYKit/Base/UIKit/UIImage+YYAdd.m
  63. 63 0
      YYKit/Base/UIKit/UIScreen+YYAdd.h
  64. 174 0
      YYKit/Base/UIKit/UIScreen+YYAdd.m
  65. 71 0
      YYKit/Base/UIKit/UIScrollView+YYAdd.h
  66. 60 0
      YYKit/Base/UIKit/UIScrollView+YYAdd.m
  67. 188 0
      YYKit/Base/UIKit/UITableView+YYAdd.h
  68. 80 0
      YYKit/Base/UIKit/UITableView+YYAdd.m
  69. 35 0
      YYKit/Base/UIKit/UITextField+YYAdd.h
  70. 33 0
      YYKit/Base/UIKit/UITextField+YYAdd.m
  71. 117 0
      YYKit/Base/UIKit/UIView+YYAdd.h
  72. 272 0
      YYKit/Base/UIKit/UIView+YYAdd.m
  73. 336 0
      YYKit/Base/YYKitMacro.h
  74. 191 0
      YYKit/Cache/YYCache.h
  75. 139 0
      YYKit/Cache/YYCache.m
  76. 412 0
      YYKit/Cache/YYDiskCache.h
  77. 444 0
      YYKit/Cache/YYDiskCache.m
  78. 325 0
      YYKit/Cache/YYKVStorage.h
  79. 1053 0
      YYKit/Cache/YYKVStorage.m
  80. 213 0
      YYKit/Cache/YYMemoryCache.h
  81. 514 0
      YYKit/Cache/YYMemoryCache.m
  82. 112 0
      YYKit/Image/Categories/CALayer+YYWebImage.h
  83. 189 0
      YYKit/Image/Categories/CALayer+YYWebImage.m
  84. 109 0
      YYKit/Image/Categories/MKAnnotationView+YYWebImage.h
  85. 186 0
      YYKit/Image/Categories/MKAnnotationView+YYWebImage.m
  86. 213 0
      YYKit/Image/Categories/UIButton+YYWebImage.h
  87. 430 0
      YYKit/Image/Categories/UIButton+YYWebImage.m
  88. 193 0
      YYKit/Image/Categories/UIImageView+YYWebImage.h
  89. 358 0
      YYKit/Image/Categories/UIImageView+YYWebImage.m
  90. 54 0
      YYKit/Image/Categories/_YYWebImageSetter.h
  91. 103 0
      YYKit/Image/Categories/_YYWebImageSetter.m
  92. 125 0
      YYKit/Image/YYAnimatedImageView.h
  93. 578 0
      YYKit/Image/YYAnimatedImageView.m
  94. 107 0
      YYKit/Image/YYFrameImage.h
  95. 120 0
      YYKit/Image/YYFrameImage.m
  96. 80 0
      YYKit/Image/YYImage.h
  97. 183 0
      YYKit/Image/YYImage.m
  98. 228 0
      YYKit/Image/YYImageCache.h
  99. 255 0
      YYKit/Image/YYImageCache.m
  100. 505 0
      YYKit/Image/YYImageCoder.h

+ 22 - 0
LICENSE

@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 ibireme <ibireme@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+

+ 187 - 0
README.md

@@ -0,0 +1,187 @@
+YYKit
+==============
+
+[![License MIT](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/ibireme/YYKit/master/LICENSE)&nbsp;
+[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)&nbsp;
+[![CocoaPods](http://img.shields.io/cocoapods/v/YYKit.svg?style=flat)](http://cocoapods.org/?q=YYKit)&nbsp;
+[![CocoaPods](http://img.shields.io/cocoapods/p/YYKit.svg?style=flat)](http://cocoapods.org/?q=YYKit)&nbsp;
+[![Support](https://img.shields.io/badge/support-iOS%206%2B%20-blue.svg?style=flat)](https://www.apple.com/nl/ios/)&nbsp;
+[![Build Status](https://travis-ci.org/ibireme/YYKit.svg?branch=master)](https://travis-ci.org/ibireme/YYKit)
+
+
+YYKit is a collection of iOS components.
+
+It's so huge that I split it into several independent components:
+
+* [YYModel](https://github.com/ibireme/YYModel) — High performance model framework for iOS.
+* [YYCache](https://github.com/ibireme/YYCache) — High performance cache framework for iOS.
+* [YYImage](https://github.com/ibireme/YYImage) — Image framework for iOS to display/encode/decode animated WebP, APNG, GIF.
+* [YYWebImage](https://github.com/ibireme/YYWebImage) — Asynchronous image loading framework.
+* [YYText](https://github.com/ibireme/YYText) — Powerful rich text component for iOS.
+* [YYKeyboardManager](https://github.com/ibireme/YYKeyboardManager) — Access keyboard view and track keyboard animation.
+* [YYDispatchQueuePool](https://github.com/ibireme/YYDispatchQueuePool) — iOS utility class to manage global dispatch queue.
+* [YYAsyncLayer](https://github.com/ibireme/YYAsyncLayer) — iOS utility classes for asynchronous rendering and display.
+* [YYCategories](https://github.com/ibireme/YYCategories) — A set of useful categories for Foundation and UIKit.
+
+
+Demo Project
+==============
+See `Demo/YYKitDemo.xcodeproj`
+
+<img src="https://raw.github.com/ibireme/YYKit/master/Demo/Snapshots/twitter.png" width="320"><br/>
+<img src="https://raw.github.com/ibireme/YYKit/master/Demo/Snapshots/weibo.png" width="320"> <img src="https://raw.github.com/ibireme/YYKit/master/Demo/Snapshots/weibo_compose.png" width="320">
+
+
+Installation
+==============
+
+### CocoaPods
+
+1. Add `pod 'YYKit'` to your Podfile.
+2. Run `pod install` or `pod update`.
+3. Import \<YYKit/YYKit.h\>.
+
+
+### Carthage
+
+1. Add `github "ibireme/YYKit"` to your Cartfile.
+2. Run `carthage update --platform ios` and add the framework to your project.
+3. Import \<YYKit/YYKit.h\>.
+4. Notice: carthage framework doesn't include webp component, if you want to support webp, use CocoaPods or install manually.
+
+### Manually
+
+1. Download all the files in the `YYKit` subdirectory.
+2. Add the source files to your Xcode project.
+3. Add `-fno-objc-arc` compiler flag to `NSObject+YYAddForARC.m` and `NSThread+YYAdd.m`.
+4. Link with required frameworks:
+    * UIKit
+    * CoreFoundation
+    * CoreText
+    * CoreGraphics
+    * CoreImage
+    * QuartzCore
+    * ImageIO
+    * AssetsLibrary
+    * Accelerate
+    * MobileCoreServices
+    * SystemConfiguration
+    * sqlite3
+    * libz
+5. Add `Vendor/WebP.framework`(static library) to your Xcode project if you want to support WebP.
+6. Import `YYKit.h`.
+
+
+Documentation
+==============
+Full API documentation is available on [CocoaDocs](http://cocoadocs.org/docsets/YYKit/).<br/>
+You can also install documentation locally using [appledoc](https://github.com/tomaz/appledoc).
+
+
+Requirements
+==============
+This library requires `iOS 6.0+` and `Xcode 7.0+`.
+
+Notice
+==============
+I want to use the APIs as if it was provided by system, and I don't add prefix in
+these categories. I do not recommend using the `YYKit` directly, you should try the separated components first.
+
+License
+==============
+YYKit is provided under the MIT license. See LICENSE file for details.
+
+
+<br/>
+---
+中文介绍
+==============
+
+YYKit 是一组庞大、功能丰富的 iOS 组件。
+
+为了尽量复用代码,这个项目中的某些组件之间有比较强的依赖关系。为了方便其他开发者使用,我从中拆分出以下独立组件:
+
+* [YYModel](https://github.com/ibireme/YYModel) — 高性能的 iOS JSON 模型框架。
+* [YYCache](https://github.com/ibireme/YYCache) — 高性能的 iOS 缓存框架。
+* [YYImage](https://github.com/ibireme/YYImage) — 功能强大的 iOS 图像框架。
+* [YYWebImage](https://github.com/ibireme/YYWebImage) — 高性能的 iOS 异步图像加载框架。
+* [YYText](https://github.com/ibireme/YYText) — 功能强大的 iOS 富文本框架。
+* [YYKeyboardManager](https://github.com/ibireme/YYKeyboardManager) — iOS 键盘监听管理工具。
+* [YYDispatchQueuePool](https://github.com/ibireme/YYDispatchQueuePool) — iOS 全局并发队列管理工具。
+* [YYAsyncLayer](https://github.com/ibireme/YYAsyncLayer) — iOS 异步绘制与显示的工具。
+* [YYCategories](https://github.com/ibireme/YYCategories) — 功能丰富的 Category 类型工具库。
+
+
+演示项目
+==============
+查看并运行 `Demo/YYKitDemo.xcodeproj`
+
+<img src="https://raw.github.com/ibireme/YYKit/master/Demo/Snapshots/twitter.png" width="320"><br/>
+<img src="https://raw.github.com/ibireme/YYKit/master/Demo/Snapshots/weibo.png" width="320"> <img src="https://raw.github.com/ibireme/YYKit/master/Demo/Snapshots/weibo_compose.png" width="320">
+
+
+安装
+==============
+
+### CocoaPods
+
+1. 在 Podfile 中添加  `pod 'YYKit'`。
+2. 执行 `pod install` 或 `pod update`。
+3. 导入 \<YYKit/YYKit.h\>。
+
+
+### Carthage
+
+1. 在 Cartfile 中添加 `github "ibireme/YYKit"`。
+2. 执行 `carthage update --platform ios` 并将生成的 framework 添加到你的工程。
+3. 导入 \<YYKit/YYKit.h\>。
+4. 注意: carthage framework 并没有包含 webp 组件。如果你需要支持 webp,可以用 CocoaPods 安装,或者手动安装。
+
+### 手动安装
+
+1. 下载 YYKit 文件夹内的所有内容。
+2. 将 YYKit 内的源文件添加(拖放)到你的工程。
+3. 为 `NSObject+YYAddForARC.m` 和 `NSThread+YYAdd.m` 添加编译参数 `-fno-objc-arc`。
+4. 链接以下 frameworks:
+    * UIKit
+    * CoreFoundation
+    * CoreText
+    * CoreGraphics
+    * CoreImage
+    * QuartzCore
+    * ImageIO
+    * AssetsLibrary
+    * Accelerate
+    * MobileCoreServices
+    * SystemConfiguration
+    * sqlite3
+    * libz
+5. 如果你需要支持 WebP,可以将 `Vendor/WebP.framework`(静态库) 加入你的工程。
+6. 导入 `YYKit.h`。
+
+
+文档
+==============
+你可以在 [CocoaDocs](http://cocoadocs.org/docsets/YYKit/) 查看在线 API 文档,也可以用 [appledoc](https://github.com/tomaz/appledoc) 本地生成文档。
+
+系统要求
+==============
+该项目最低支持 `iOS 6.0` 和 `Xcode 7.0`。
+
+
+注意
+==============
+我希望调用 API 时,有着和调用系统自带 API 一样的体验,所以我并没有为 Category 方法添加前缀。我已经用工具扫描过这个项目中的 API,确保没有对系统 API 产生影响,但即使这样没有前缀的 Category 也可能会带来其他麻烦。因此我不太推荐直接使用 `YYKit` 这个库,你应该先尝试一下上面那些拆分出来的独立组件。 
+
+
+许可证
+==============
+YYKit 使用 MIT 许可证,详情见 LICENSE 文件。
+
+
+相关文章
+==============
+[iOS 保持界面流畅的技巧
+](http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/) 
+
+

+ 145 - 0
Vendor/WebP.framework/Headers/config.h

@@ -0,0 +1,145 @@
+/* src/webp/config.h.  Generated from config.h.in by configure.  */
+/* src/webp/config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Set to 1 if __builtin_bswap16 is available */
+#define HAVE_BUILTIN_BSWAP16 1
+
+/* Set to 1 if __builtin_bswap32 is available */
+#define HAVE_BUILTIN_BSWAP32 1
+
+/* Set to 1 if __builtin_bswap64 is available */
+#define HAVE_BUILTIN_BSWAP64 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if you have the <GLUT/glut.h> header file. */
+/* #undef HAVE_GLUT_GLUT_H */
+
+/* Define to 1 if you have the <GL/glut.h> header file. */
+/* #undef HAVE_GL_GLUT_H */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the <OpenGL/glut.h> header file. */
+/* #undef HAVE_OPENGL_GLUT_H */
+
+/* Have PTHREAD_PRIO_INHERIT. */
+#define HAVE_PTHREAD_PRIO_INHERIT 1
+
+/* Define to 1 if you have the <shlwapi.h> header file. */
+/* #undef HAVE_SHLWAPI_H */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the <wincodec.h> header file. */
+/* #undef HAVE_WINCODEC_H */
+
+/* Define to 1 if you have the <windows.h> header file. */
+/* #undef HAVE_WINDOWS_H */
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+   */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libwebp"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "https://bugs.chromium.org/p/webp"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libwebp"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libwebp 0.5.0"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libwebp"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL "http://developers.google.com/speed/webp"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "0.5.0"
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+   your system. */
+/* #undef PTHREAD_CREATE_JOINABLE */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Version number of package */
+#define VERSION "0.5.0"
+
+/* Enable experimental code */
+/* #undef WEBP_EXPERIMENTAL_FEATURES */
+
+/* Define to 1 to force aligned memory operations */
+/* #undef WEBP_FORCE_ALIGNED */
+
+/* Set to 1 if AVX2 is supported */
+/* #undef WEBP_HAVE_AVX2 */
+
+/* Set to 1 if GIF library is installed */
+/* #undef WEBP_HAVE_GIF */
+
+/* Set to 1 if OpenGL is supported */
+/* #undef WEBP_HAVE_GL */
+
+/* Set to 1 if JPEG library is installed */
+/* #undef WEBP_HAVE_JPEG */
+
+/* Set to 1 if PNG library is installed */
+/* #undef WEBP_HAVE_PNG */
+
+/* Set to 1 if SSE2 is supported */
+/* #undef WEBP_HAVE_SSE2 */
+
+/* Set to 1 if SSE4.1 is supported */
+/* #undef WEBP_HAVE_SSE41 */
+
+/* Set to 1 if TIFF library is installed */
+/* #undef WEBP_HAVE_TIFF */
+
+/* Undefine this to disable thread support. */
+#define WEBP_USE_THREAD 1
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+   significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+#  define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* #  undef WORDS_BIGENDIAN */
+# endif
+#endif

+ 488 - 0
Vendor/WebP.framework/Headers/decode.h

@@ -0,0 +1,488 @@
+// Copyright 2010 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+//  Main decoding functions for WebP images.
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#ifndef WEBP_WEBP_DECODE_H_
+#define WEBP_WEBP_DECODE_H_
+
+#include "./types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define WEBP_DECODER_ABI_VERSION 0x0208    // MAJOR(8b) + MINOR(8b)
+
+// Note: forward declaring enumerations is not allowed in (strict) C and C++,
+// the types are left here for reference.
+// typedef enum VP8StatusCode VP8StatusCode;
+// typedef enum WEBP_CSP_MODE WEBP_CSP_MODE;
+typedef struct WebPRGBABuffer WebPRGBABuffer;
+typedef struct WebPYUVABuffer WebPYUVABuffer;
+typedef struct WebPDecBuffer WebPDecBuffer;
+typedef struct WebPIDecoder WebPIDecoder;
+typedef struct WebPBitstreamFeatures WebPBitstreamFeatures;
+typedef struct WebPDecoderOptions WebPDecoderOptions;
+typedef struct WebPDecoderConfig WebPDecoderConfig;
+
+// Return the decoder's version number, packed in hexadecimal using 8bits for
+// each of major/minor/revision. E.g: v2.5.7 is 0x020507.
+WEBP_EXTERN(int) WebPGetDecoderVersion(void);
+
+// Retrieve basic header information: width, height.
+// This function will also validate the header and return 0 in
+// case of formatting error.
+// Pointers 'width' and 'height' can be passed NULL if deemed irrelevant.
+WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size,
+                             int* width, int* height);
+
+// Decodes WebP images pointed to by 'data' and returns RGBA samples, along
+// with the dimensions in *width and *height. The ordering of samples in
+// memory is R, G, B, A, R, G, B, A... in scan order (endian-independent).
+// The returned pointer should be deleted calling WebPFree().
+// Returns NULL in case of error.
+WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size,
+                                     int* width, int* height);
+
+// Same as WebPDecodeRGBA, but returning A, R, G, B, A, R, G, B... ordered data.
+WEBP_EXTERN(uint8_t*) WebPDecodeARGB(const uint8_t* data, size_t data_size,
+                                     int* width, int* height);
+
+// Same as WebPDecodeRGBA, but returning B, G, R, A, B, G, R, A... ordered data.
+WEBP_EXTERN(uint8_t*) WebPDecodeBGRA(const uint8_t* data, size_t data_size,
+                                     int* width, int* height);
+
+// Same as WebPDecodeRGBA, but returning R, G, B, R, G, B... ordered data.
+// If the bitstream contains transparency, it is ignored.
+WEBP_EXTERN(uint8_t*) WebPDecodeRGB(const uint8_t* data, size_t data_size,
+                                    int* width, int* height);
+
+// Same as WebPDecodeRGB, but returning B, G, R, B, G, R... ordered data.
+WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size,
+                                    int* width, int* height);
+
+
+// Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer
+// returned is the Y samples buffer. Upon return, *u and *v will point to
+// the U and V chroma data. These U and V buffers need NOT be passed to
+// WebPFree(), unlike the returned Y luma one. The dimension of the U and V
+// planes are both (*width + 1) / 2 and (*height + 1)/ 2.
+// Upon return, the Y buffer has a stride returned as '*stride', while U and V
+// have a common stride returned as '*uv_stride'.
+// Return NULL in case of error.
+// (*) Also named Y'CbCr. See: http://en.wikipedia.org/wiki/YCbCr
+WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size,
+                                    int* width, int* height,
+                                    uint8_t** u, uint8_t** v,
+                                    int* stride, int* uv_stride);
+
+// Releases memory returned by the WebPDecode*() functions above.
+WEBP_EXTERN(void) WebPFree(void* ptr);
+
+// These five functions are variants of the above ones, that decode the image
+// directly into a pre-allocated buffer 'output_buffer'. The maximum storage
+// available in this buffer is indicated by 'output_buffer_size'. If this
+// storage is not sufficient (or an error occurred), NULL is returned.
+// Otherwise, output_buffer is returned, for convenience.
+// The parameter 'output_stride' specifies the distance (in bytes)
+// between scanlines. Hence, output_buffer_size is expected to be at least
+// output_stride x picture-height.
+WEBP_EXTERN(uint8_t*) WebPDecodeRGBAInto(
+    const uint8_t* data, size_t data_size,
+    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
+WEBP_EXTERN(uint8_t*) WebPDecodeARGBInto(
+    const uint8_t* data, size_t data_size,
+    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
+WEBP_EXTERN(uint8_t*) WebPDecodeBGRAInto(
+    const uint8_t* data, size_t data_size,
+    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
+
+// RGB and BGR variants. Here too the transparency information, if present,
+// will be dropped and ignored.
+WEBP_EXTERN(uint8_t*) WebPDecodeRGBInto(
+    const uint8_t* data, size_t data_size,
+    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
+WEBP_EXTERN(uint8_t*) WebPDecodeBGRInto(
+    const uint8_t* data, size_t data_size,
+    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
+
+// WebPDecodeYUVInto() is a variant of WebPDecodeYUV() that operates directly
+// into pre-allocated luma/chroma plane buffers. This function requires the
+// strides to be passed: one for the luma plane and one for each of the
+// chroma ones. The size of each plane buffer is passed as 'luma_size',
+// 'u_size' and 'v_size' respectively.
+// Pointer to the luma plane ('*luma') is returned or NULL if an error occurred
+// during decoding (or because some buffers were found to be too small).
+WEBP_EXTERN(uint8_t*) WebPDecodeYUVInto(
+    const uint8_t* data, size_t data_size,
+    uint8_t* luma, size_t luma_size, int luma_stride,
+    uint8_t* u, size_t u_size, int u_stride,
+    uint8_t* v, size_t v_size, int v_stride);
+
+//------------------------------------------------------------------------------
+// Output colorspaces and buffer
+
+// Colorspaces
+// Note: the naming describes the byte-ordering of packed samples in memory.
+// For instance, MODE_BGRA relates to samples ordered as B,G,R,A,B,G,R,A,...
+// Non-capital names (e.g.:MODE_Argb) relates to pre-multiplied RGB channels.
+// RGBA-4444 and RGB-565 colorspaces are represented by following byte-order:
+// RGBA-4444: [r3 r2 r1 r0 g3 g2 g1 g0], [b3 b2 b1 b0 a3 a2 a1 a0], ...
+// RGB-565: [r4 r3 r2 r1 r0 g5 g4 g3], [g2 g1 g0 b4 b3 b2 b1 b0], ...
+// In the case WEBP_SWAP_16BITS_CSP is defined, the bytes are swapped for
+// these two modes:
+// RGBA-4444: [b3 b2 b1 b0 a3 a2 a1 a0], [r3 r2 r1 r0 g3 g2 g1 g0], ...
+// RGB-565: [g2 g1 g0 b4 b3 b2 b1 b0], [r4 r3 r2 r1 r0 g5 g4 g3], ...
+
+typedef enum WEBP_CSP_MODE {
+  MODE_RGB = 0, MODE_RGBA = 1,
+  MODE_BGR = 2, MODE_BGRA = 3,
+  MODE_ARGB = 4, MODE_RGBA_4444 = 5,
+  MODE_RGB_565 = 6,
+  // RGB-premultiplied transparent modes (alpha value is preserved)
+  MODE_rgbA = 7,
+  MODE_bgrA = 8,
+  MODE_Argb = 9,
+  MODE_rgbA_4444 = 10,
+  // YUV modes must come after RGB ones.
+  MODE_YUV = 11, MODE_YUVA = 12,  // yuv 4:2:0
+  MODE_LAST = 13
+} WEBP_CSP_MODE;
+
+// Some useful macros:
+static WEBP_INLINE int WebPIsPremultipliedMode(WEBP_CSP_MODE mode) {
+  return (mode == MODE_rgbA || mode == MODE_bgrA || mode == MODE_Argb ||
+          mode == MODE_rgbA_4444);
+}
+
+static WEBP_INLINE int WebPIsAlphaMode(WEBP_CSP_MODE mode) {
+  return (mode == MODE_RGBA || mode == MODE_BGRA || mode == MODE_ARGB ||
+          mode == MODE_RGBA_4444 || mode == MODE_YUVA ||
+          WebPIsPremultipliedMode(mode));
+}
+
+static WEBP_INLINE int WebPIsRGBMode(WEBP_CSP_MODE mode) {
+  return (mode < MODE_YUV);
+}
+
+//------------------------------------------------------------------------------
+// WebPDecBuffer: Generic structure for describing the output sample buffer.
+
+struct WebPRGBABuffer {    // view as RGBA
+  uint8_t* rgba;    // pointer to RGBA samples
+  int stride;       // stride in bytes from one scanline to the next.
+  size_t size;      // total size of the *rgba buffer.
+};
+
+struct WebPYUVABuffer {              // view as YUVA
+  uint8_t* y, *u, *v, *a;     // pointer to luma, chroma U/V, alpha samples
+  int y_stride;               // luma stride
+  int u_stride, v_stride;     // chroma strides
+  int a_stride;               // alpha stride
+  size_t y_size;              // luma plane size
+  size_t u_size, v_size;      // chroma planes size
+  size_t a_size;              // alpha-plane size
+};
+
+// Output buffer
+struct WebPDecBuffer {
+  WEBP_CSP_MODE colorspace;  // Colorspace.
+  int width, height;         // Dimensions.
+  int is_external_memory;    // If true, 'internal_memory' pointer is not used.
+  union {
+    WebPRGBABuffer RGBA;
+    WebPYUVABuffer YUVA;
+  } u;                       // Nameless union of buffer parameters.
+  uint32_t       pad[4];     // padding for later use
+
+  uint8_t* private_memory;   // Internally allocated memory (only when
+                             // is_external_memory is false). Should not be used
+                             // externally, but accessed via the buffer union.
+};
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(int) WebPInitDecBufferInternal(WebPDecBuffer*, int);
+
+// Initialize the structure as empty. Must be called before any other use.
+// Returns false in case of version mismatch
+static WEBP_INLINE int WebPInitDecBuffer(WebPDecBuffer* buffer) {
+  return WebPInitDecBufferInternal(buffer, WEBP_DECODER_ABI_VERSION);
+}
+
+// Free any memory associated with the buffer. Must always be called last.
+// Note: doesn't free the 'buffer' structure itself.
+WEBP_EXTERN(void) WebPFreeDecBuffer(WebPDecBuffer* buffer);
+
+//------------------------------------------------------------------------------
+// Enumeration of the status codes
+
+typedef enum VP8StatusCode {
+  VP8_STATUS_OK = 0,
+  VP8_STATUS_OUT_OF_MEMORY,
+  VP8_STATUS_INVALID_PARAM,
+  VP8_STATUS_BITSTREAM_ERROR,
+  VP8_STATUS_UNSUPPORTED_FEATURE,
+  VP8_STATUS_SUSPENDED,
+  VP8_STATUS_USER_ABORT,
+  VP8_STATUS_NOT_ENOUGH_DATA
+} VP8StatusCode;
+
+//------------------------------------------------------------------------------
+// Incremental decoding
+//
+// This API allows streamlined decoding of partial data.
+// Picture can be incrementally decoded as data become available thanks to the
+// WebPIDecoder object. This object can be left in a SUSPENDED state if the
+// picture is only partially decoded, pending additional input.
+// Code example:
+//
+//   WebPInitDecBuffer(&buffer);
+//   buffer.colorspace = mode;
+//   ...
+//   WebPIDecoder* idec = WebPINewDecoder(&buffer);
+//   while (has_more_data) {
+//     // ... (get additional data)
+//     status = WebPIAppend(idec, new_data, new_data_size);
+//     if (status != VP8_STATUS_SUSPENDED ||
+//       break;
+//     }
+//
+//     // The above call decodes the current available buffer.
+//     // Part of the image can now be refreshed by calling to
+//     // WebPIDecGetRGB()/WebPIDecGetYUVA() etc.
+//   }
+//   WebPIDelete(idec);
+
+// Creates a new incremental decoder with the supplied buffer parameter.
+// This output_buffer can be passed NULL, in which case a default output buffer
+// is used (with MODE_RGB). Otherwise, an internal reference to 'output_buffer'
+// is kept, which means that the lifespan of 'output_buffer' must be larger than
+// that of the returned WebPIDecoder object.
+// The supplied 'output_buffer' content MUST NOT be changed between calls to
+// WebPIAppend() or WebPIUpdate() unless 'output_buffer.is_external_memory' is
+// set to 1. In such a case, it is allowed to modify the pointers, size and
+// stride of output_buffer.u.RGBA or output_buffer.u.YUVA, provided they remain
+// within valid bounds.
+// All other fields of WebPDecBuffer MUST remain constant between calls.
+// Returns NULL if the allocation failed.
+WEBP_EXTERN(WebPIDecoder*) WebPINewDecoder(WebPDecBuffer* output_buffer);
+
+// This function allocates and initializes an incremental-decoder object, which
+// will output the RGB/A samples specified by 'csp' into a preallocated
+// buffer 'output_buffer'. The size of this buffer is at least
+// 'output_buffer_size' and the stride (distance in bytes between two scanlines)
+// is specified by 'output_stride'.
+// Additionally, output_buffer can be passed NULL in which case the output
+// buffer will be allocated automatically when the decoding starts. The
+// colorspace 'csp' is taken into account for allocating this buffer. All other
+// parameters are ignored.
+// Returns NULL if the allocation failed, or if some parameters are invalid.
+WEBP_EXTERN(WebPIDecoder*) WebPINewRGB(
+    WEBP_CSP_MODE csp,
+    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
+
+// This function allocates and initializes an incremental-decoder object, which
+// will output the raw luma/chroma samples into a preallocated planes if
+// supplied. The luma plane is specified by its pointer 'luma', its size
+// 'luma_size' and its stride 'luma_stride'. Similarly, the chroma-u plane
+// is specified by the 'u', 'u_size' and 'u_stride' parameters, and the chroma-v
+// plane by 'v' and 'v_size'. And same for the alpha-plane. The 'a' pointer
+// can be pass NULL in case one is not interested in the transparency plane.
+// Conversely, 'luma' can be passed NULL if no preallocated planes are supplied.
+// In this case, the output buffer will be automatically allocated (using
+// MODE_YUVA) when decoding starts. All parameters are then ignored.
+// Returns NULL if the allocation failed or if a parameter is invalid.
+WEBP_EXTERN(WebPIDecoder*) WebPINewYUVA(
+    uint8_t* luma, size_t luma_size, int luma_stride,
+    uint8_t* u, size_t u_size, int u_stride,
+    uint8_t* v, size_t v_size, int v_stride,
+    uint8_t* a, size_t a_size, int a_stride);
+
+// Deprecated version of the above, without the alpha plane.
+// Kept for backward compatibility.
+WEBP_EXTERN(WebPIDecoder*) WebPINewYUV(
+    uint8_t* luma, size_t luma_size, int luma_stride,
+    uint8_t* u, size_t u_size, int u_stride,
+    uint8_t* v, size_t v_size, int v_stride);
+
+// Deletes the WebPIDecoder object and associated memory. Must always be called
+// if WebPINewDecoder, WebPINewRGB or WebPINewYUV succeeded.
+WEBP_EXTERN(void) WebPIDelete(WebPIDecoder* idec);
+
+// Copies and decodes the next available data. Returns VP8_STATUS_OK when
+// the image is successfully decoded. Returns VP8_STATUS_SUSPENDED when more
+// data is expected. Returns error in other cases.
+WEBP_EXTERN(VP8StatusCode) WebPIAppend(
+    WebPIDecoder* idec, const uint8_t* data, size_t data_size);
+
+// A variant of the above function to be used when data buffer contains
+// partial data from the beginning. In this case data buffer is not copied
+// to the internal memory.
+// Note that the value of the 'data' pointer can change between calls to
+// WebPIUpdate, for instance when the data buffer is resized to fit larger data.
+WEBP_EXTERN(VP8StatusCode) WebPIUpdate(
+    WebPIDecoder* idec, const uint8_t* data, size_t data_size);
+
+// Returns the RGB/A image decoded so far. Returns NULL if output params
+// are not initialized yet. The RGB/A output type corresponds to the colorspace
+// specified during call to WebPINewDecoder() or WebPINewRGB().
+// *last_y is the index of last decoded row in raster scan order. Some pointers
+// (*last_y, *width etc.) can be NULL if corresponding information is not
+// needed.
+WEBP_EXTERN(uint8_t*) WebPIDecGetRGB(
+    const WebPIDecoder* idec, int* last_y,
+    int* width, int* height, int* stride);
+
+// Same as above function to get a YUVA image. Returns pointer to the luma
+// plane or NULL in case of error. If there is no alpha information
+// the alpha pointer '*a' will be returned NULL.
+WEBP_EXTERN(uint8_t*) WebPIDecGetYUVA(
+    const WebPIDecoder* idec, int* last_y,
+    uint8_t** u, uint8_t** v, uint8_t** a,
+    int* width, int* height, int* stride, int* uv_stride, int* a_stride);
+
+// Deprecated alpha-less version of WebPIDecGetYUVA(): it will ignore the
+// alpha information (if present). Kept for backward compatibility.
+static WEBP_INLINE uint8_t* WebPIDecGetYUV(
+    const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v,
+    int* width, int* height, int* stride, int* uv_stride) {
+  return WebPIDecGetYUVA(idec, last_y, u, v, NULL, width, height,
+                         stride, uv_stride, NULL);
+}
+
+// Generic call to retrieve information about the displayable area.
+// If non NULL, the left/right/width/height pointers are filled with the visible
+// rectangular area so far.
+// Returns NULL in case the incremental decoder object is in an invalid state.
+// Otherwise returns the pointer to the internal representation. This structure
+// is read-only, tied to WebPIDecoder's lifespan and should not be modified.
+WEBP_EXTERN(const WebPDecBuffer*) WebPIDecodedArea(
+    const WebPIDecoder* idec, int* left, int* top, int* width, int* height);
+
+//------------------------------------------------------------------------------
+// Advanced decoding parametrization
+//
+//  Code sample for using the advanced decoding API
+/*
+     // A) Init a configuration object
+     WebPDecoderConfig config;
+     CHECK(WebPInitDecoderConfig(&config));
+
+     // B) optional: retrieve the bitstream's features.
+     CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);
+
+     // C) Adjust 'config', if needed
+     config.no_fancy_upsampling = 1;
+     config.output.colorspace = MODE_BGRA;
+     // etc.
+
+     // Note that you can also make config.output point to an externally
+     // supplied memory buffer, provided it's big enough to store the decoded
+     // picture. Otherwise, config.output will just be used to allocate memory
+     // and store the decoded picture.
+
+     // D) Decode!
+     CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK);
+
+     // E) Decoded image is now in config.output (and config.output.u.RGBA)
+
+     // F) Reclaim memory allocated in config's object. It's safe to call
+     // this function even if the memory is external and wasn't allocated
+     // by WebPDecode().
+     WebPFreeDecBuffer(&config.output);
+*/
+
+// Features gathered from the bitstream
+struct WebPBitstreamFeatures {
+  int width;          // Width in pixels, as read from the bitstream.
+  int height;         // Height in pixels, as read from the bitstream.
+  int has_alpha;      // True if the bitstream contains an alpha channel.
+  int has_animation;  // True if the bitstream is an animation.
+  int format;         // 0 = undefined (/mixed), 1 = lossy, 2 = lossless
+
+  uint32_t pad[5];    // padding for later use
+};
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(VP8StatusCode) WebPGetFeaturesInternal(
+    const uint8_t*, size_t, WebPBitstreamFeatures*, int);
+
+// Retrieve features from the bitstream. The *features structure is filled
+// with information gathered from the bitstream.
+// Returns VP8_STATUS_OK when the features are successfully retrieved. Returns
+// VP8_STATUS_NOT_ENOUGH_DATA when more data is needed to retrieve the
+// features from headers. Returns error in other cases.
+static WEBP_INLINE VP8StatusCode WebPGetFeatures(
+    const uint8_t* data, size_t data_size,
+    WebPBitstreamFeatures* features) {
+  return WebPGetFeaturesInternal(data, data_size, features,
+                                 WEBP_DECODER_ABI_VERSION);
+}
+
+// Decoding options
+struct WebPDecoderOptions {
+  int bypass_filtering;               // if true, skip the in-loop filtering
+  int no_fancy_upsampling;            // if true, use faster pointwise upsampler
+  int use_cropping;                   // if true, cropping is applied _first_
+  int crop_left, crop_top;            // top-left position for cropping.
+                                      // Will be snapped to even values.
+  int crop_width, crop_height;        // dimension of the cropping area
+  int use_scaling;                    // if true, scaling is applied _afterward_
+  int scaled_width, scaled_height;    // final resolution
+  int use_threads;                    // if true, use multi-threaded decoding
+  int dithering_strength;             // dithering strength (0=Off, 100=full)
+  int flip;                           // flip output vertically
+  int alpha_dithering_strength;       // alpha dithering strength in [0..100]
+
+  uint32_t pad[5];                    // padding for later use
+};
+
+// Main object storing the configuration for advanced decoding.
+struct WebPDecoderConfig {
+  WebPBitstreamFeatures input;  // Immutable bitstream features (optional)
+  WebPDecBuffer output;         // Output buffer (can point to external mem)
+  WebPDecoderOptions options;   // Decoding options
+};
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(int) WebPInitDecoderConfigInternal(WebPDecoderConfig*, int);
+
+// Initialize the configuration as empty. This function must always be
+// called first, unless WebPGetFeatures() is to be called.
+// Returns false in case of mismatched version.
+static WEBP_INLINE int WebPInitDecoderConfig(WebPDecoderConfig* config) {
+  return WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION);
+}
+
+// Instantiate a new incremental decoder object with the requested
+// configuration. The bitstream can be passed using 'data' and 'data_size'
+// parameter, in which case the features will be parsed and stored into
+// config->input. Otherwise, 'data' can be NULL and no parsing will occur.
+// Note that 'config' can be NULL too, in which case a default configuration
+// is used.
+// The return WebPIDecoder object must always be deleted calling WebPIDelete().
+// Returns NULL in case of error (and config->status will then reflect
+// the error condition).
+WEBP_EXTERN(WebPIDecoder*) WebPIDecode(const uint8_t* data, size_t data_size,
+                                       WebPDecoderConfig* config);
+
+// Non-incremental version. This version decodes the full data at once, taking
+// 'config' into account. Returns decoding status (which should be VP8_STATUS_OK
+// if the decoding was successful).
+WEBP_EXTERN(VP8StatusCode) WebPDecode(const uint8_t* data, size_t data_size,
+                                      WebPDecoderConfig* config);
+
+#ifdef __cplusplus
+}    // extern "C"
+#endif
+
+#endif  /* WEBP_WEBP_DECODE_H_ */

+ 358 - 0
Vendor/WebP.framework/Headers/demux.h

@@ -0,0 +1,358 @@
+// Copyright 2012 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Demux API.
+// Enables extraction of image and extended format data from WebP files.
+
+// Code Example: Demuxing WebP data to extract all the frames, ICC profile
+// and EXIF/XMP metadata.
+/*
+  WebPDemuxer* demux = WebPDemux(&webp_data);
+
+  uint32_t width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH);
+  uint32_t height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT);
+  // ... (Get information about the features present in the WebP file).
+  uint32_t flags = WebPDemuxGetI(demux, WEBP_FF_FORMAT_FLAGS);
+
+  // ... (Iterate over all frames).
+  WebPIterator iter;
+  if (WebPDemuxGetFrame(demux, 1, &iter)) {
+    do {
+      // ... (Consume 'iter'; e.g. Decode 'iter.fragment' with WebPDecode(),
+      // ... and get other frame properties like width, height, offsets etc.
+      // ... see 'struct WebPIterator' below for more info).
+    } while (WebPDemuxNextFrame(&iter));
+    WebPDemuxReleaseIterator(&iter);
+  }
+
+  // ... (Extract metadata).
+  WebPChunkIterator chunk_iter;
+  if (flags & ICCP_FLAG) WebPDemuxGetChunk(demux, "ICCP", 1, &chunk_iter);
+  // ... (Consume the ICC profile in 'chunk_iter.chunk').
+  WebPDemuxReleaseChunkIterator(&chunk_iter);
+  if (flags & EXIF_FLAG) WebPDemuxGetChunk(demux, "EXIF", 1, &chunk_iter);
+  // ... (Consume the EXIF metadata in 'chunk_iter.chunk').
+  WebPDemuxReleaseChunkIterator(&chunk_iter);
+  if (flags & XMP_FLAG) WebPDemuxGetChunk(demux, "XMP ", 1, &chunk_iter);
+  // ... (Consume the XMP metadata in 'chunk_iter.chunk').
+  WebPDemuxReleaseChunkIterator(&chunk_iter);
+  WebPDemuxDelete(demux);
+*/
+
+#ifndef WEBP_WEBP_DEMUX_H_
+#define WEBP_WEBP_DEMUX_H_
+
+#include "./decode.h"     // for WEBP_CSP_MODE
+#include "./mux_types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define WEBP_DEMUX_ABI_VERSION 0x0107    // MAJOR(8b) + MINOR(8b)
+
+// Note: forward declaring enumerations is not allowed in (strict) C and C++,
+// the types are left here for reference.
+// typedef enum WebPDemuxState WebPDemuxState;
+// typedef enum WebPFormatFeature WebPFormatFeature;
+typedef struct WebPDemuxer WebPDemuxer;
+typedef struct WebPIterator WebPIterator;
+typedef struct WebPChunkIterator WebPChunkIterator;
+typedef struct WebPAnimInfo WebPAnimInfo;
+typedef struct WebPAnimDecoderOptions WebPAnimDecoderOptions;
+
+//------------------------------------------------------------------------------
+
+// Returns the version number of the demux library, packed in hexadecimal using
+// 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
+WEBP_EXTERN(int) WebPGetDemuxVersion(void);
+
+//------------------------------------------------------------------------------
+// Life of a Demux object
+
+typedef enum WebPDemuxState {
+  WEBP_DEMUX_PARSE_ERROR    = -1,  // An error occurred while parsing.
+  WEBP_DEMUX_PARSING_HEADER =  0,  // Not enough data to parse full header.
+  WEBP_DEMUX_PARSED_HEADER  =  1,  // Header parsing complete,
+                                   // data may be available.
+  WEBP_DEMUX_DONE           =  2   // Entire file has been parsed.
+} WebPDemuxState;
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(WebPDemuxer*) WebPDemuxInternal(
+    const WebPData*, int, WebPDemuxState*, int);
+
+// Parses the full WebP file given by 'data'. For single images the WebP file
+// header alone or the file header and the chunk header may be absent.
+// Returns a WebPDemuxer object on successful parse, NULL otherwise.
+static WEBP_INLINE WebPDemuxer* WebPDemux(const WebPData* data) {
+  return WebPDemuxInternal(data, 0, NULL, WEBP_DEMUX_ABI_VERSION);
+}
+
+// Parses the possibly incomplete WebP file given by 'data'.
+// If 'state' is non-NULL it will be set to indicate the status of the demuxer.
+// Returns NULL in case of error or if there isn't enough data to start parsing;
+// and a WebPDemuxer object on successful parse.
+// Note that WebPDemuxer keeps internal pointers to 'data' memory segment.
+// If this data is volatile, the demuxer object should be deleted (by calling
+// WebPDemuxDelete()) and WebPDemuxPartial() called again on the new data.
+// This is usually an inexpensive operation.
+static WEBP_INLINE WebPDemuxer* WebPDemuxPartial(
+    const WebPData* data, WebPDemuxState* state) {
+  return WebPDemuxInternal(data, 1, state, WEBP_DEMUX_ABI_VERSION);
+}
+
+// Frees memory associated with 'dmux'.
+WEBP_EXTERN(void) WebPDemuxDelete(WebPDemuxer* dmux);
+
+//------------------------------------------------------------------------------
+// Data/information extraction.
+
+typedef enum WebPFormatFeature {
+  WEBP_FF_FORMAT_FLAGS,  // Extended format flags present in the 'VP8X' chunk.
+  WEBP_FF_CANVAS_WIDTH,
+  WEBP_FF_CANVAS_HEIGHT,
+  WEBP_FF_LOOP_COUNT,
+  WEBP_FF_BACKGROUND_COLOR,
+  WEBP_FF_FRAME_COUNT    // Number of frames present in the demux object.
+                         // In case of a partial demux, this is the number of
+                         // frames seen so far, with the last frame possibly
+                         // being partial.
+} WebPFormatFeature;
+
+// Get the 'feature' value from the 'dmux'.
+// NOTE: values are only valid if WebPDemux() was used or WebPDemuxPartial()
+// returned a state > WEBP_DEMUX_PARSING_HEADER.
+WEBP_EXTERN(uint32_t) WebPDemuxGetI(
+    const WebPDemuxer* dmux, WebPFormatFeature feature);
+
+//------------------------------------------------------------------------------
+// Frame iteration.
+
+struct WebPIterator {
+  int frame_num;
+  int num_frames;          // equivalent to WEBP_FF_FRAME_COUNT.
+  int x_offset, y_offset;  // offset relative to the canvas.
+  int width, height;       // dimensions of this frame.
+  int duration;            // display duration in milliseconds.
+  WebPMuxAnimDispose dispose_method;  // dispose method for the frame.
+  int complete;   // true if 'fragment' contains a full frame. partial images
+                  // may still be decoded with the WebP incremental decoder.
+  WebPData fragment;  // The frame given by 'frame_num'. Note for historical
+                      // reasons this is called a fragment.
+  int has_alpha;      // True if the frame contains transparency.
+  WebPMuxAnimBlend blend_method;  // Blend operation for the frame.
+
+  uint32_t pad[2];         // padding for later use.
+  void* private_;          // for internal use only.
+};
+
+// Retrieves frame 'frame_number' from 'dmux'.
+// 'iter->fragment' points to the frame on return from this function.
+// Setting 'frame_number' equal to 0 will return the last frame of the image.
+// Returns false if 'dmux' is NULL or frame 'frame_number' is not present.
+// Call WebPDemuxReleaseIterator() when use of the iterator is complete.
+// NOTE: 'dmux' must persist for the lifetime of 'iter'.
+WEBP_EXTERN(int) WebPDemuxGetFrame(
+    const WebPDemuxer* dmux, int frame_number, WebPIterator* iter);
+
+// Sets 'iter->fragment' to point to the next ('iter->frame_num' + 1) or
+// previous ('iter->frame_num' - 1) frame. These functions do not loop.
+// Returns true on success, false otherwise.
+WEBP_EXTERN(int) WebPDemuxNextFrame(WebPIterator* iter);
+WEBP_EXTERN(int) WebPDemuxPrevFrame(WebPIterator* iter);
+
+// Releases any memory associated with 'iter'.
+// Must be called before any subsequent calls to WebPDemuxGetChunk() on the same
+// iter. Also, must be called before destroying the associated WebPDemuxer with
+// WebPDemuxDelete().
+WEBP_EXTERN(void) WebPDemuxReleaseIterator(WebPIterator* iter);
+
+//------------------------------------------------------------------------------
+// Chunk iteration.
+
+struct WebPChunkIterator {
+  // The current and total number of chunks with the fourcc given to
+  // WebPDemuxGetChunk().
+  int chunk_num;
+  int num_chunks;
+  WebPData chunk;    // The payload of the chunk.
+
+  uint32_t pad[6];   // padding for later use
+  void* private_;
+};
+
+// Retrieves the 'chunk_number' instance of the chunk with id 'fourcc' from
+// 'dmux'.
+// 'fourcc' is a character array containing the fourcc of the chunk to return,
+// e.g., "ICCP", "XMP ", "EXIF", etc.
+// Setting 'chunk_number' equal to 0 will return the last chunk in a set.
+// Returns true if the chunk is found, false otherwise. Image related chunk
+// payloads are accessed through WebPDemuxGetFrame() and related functions.
+// Call WebPDemuxReleaseChunkIterator() when use of the iterator is complete.
+// NOTE: 'dmux' must persist for the lifetime of the iterator.
+WEBP_EXTERN(int) WebPDemuxGetChunk(const WebPDemuxer* dmux,
+                                   const char fourcc[4], int chunk_number,
+                                   WebPChunkIterator* iter);
+
+// Sets 'iter->chunk' to point to the next ('iter->chunk_num' + 1) or previous
+// ('iter->chunk_num' - 1) chunk. These functions do not loop.
+// Returns true on success, false otherwise.
+WEBP_EXTERN(int) WebPDemuxNextChunk(WebPChunkIterator* iter);
+WEBP_EXTERN(int) WebPDemuxPrevChunk(WebPChunkIterator* iter);
+
+// Releases any memory associated with 'iter'.
+// Must be called before destroying the associated WebPDemuxer with
+// WebPDemuxDelete().
+WEBP_EXTERN(void) WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter);
+
+//------------------------------------------------------------------------------
+// WebPAnimDecoder API
+//
+// This API allows decoding (possibly) animated WebP images.
+//
+// Code Example:
+/*
+  WebPAnimDecoderOptions dec_options;
+  WebPAnimDecoderOptionsInit(&dec_options);
+  // Tune 'dec_options' as needed.
+  WebPAnimDecoder* dec = WebPAnimDecoderNew(webp_data, &dec_options);
+  WebPAnimInfo anim_info;
+  WebPAnimDecoderGetInfo(dec, &anim_info);
+  for (uint32_t i = 0; i < anim_info.loop_count; ++i) {
+    while (WebPAnimDecoderHasMoreFrames(dec)) {
+      uint8_t* buf;
+      int timestamp;
+      WebPAnimDecoderGetNext(dec, &buf, &timestamp);
+      // ... (Render 'buf' based on 'timestamp').
+      // ... (Do NOT free 'buf', as it is owned by 'dec').
+    }
+    WebPAnimDecoderReset(dec);
+  }
+  const WebPDemuxer* demuxer = WebPAnimDecoderGetDemuxer(dec);
+  // ... (Do something using 'demuxer'; e.g. get EXIF/XMP/ICC data).
+  WebPAnimDecoderDelete(dec);
+*/
+
+typedef struct WebPAnimDecoder WebPAnimDecoder;  // Main opaque object.
+
+// Global options.
+struct WebPAnimDecoderOptions {
+  // Output colorspace. Only the following modes are supported:
+  // MODE_RGBA, MODE_BGRA, MODE_rgbA and MODE_bgrA.
+  WEBP_CSP_MODE color_mode;
+  int use_threads;           // If true, use multi-threaded decoding.
+  uint32_t padding[7];       // Padding for later use.
+};
+
+// Internal, version-checked, entry point.
+WEBP_EXTERN(int) WebPAnimDecoderOptionsInitInternal(
+    WebPAnimDecoderOptions*, int);
+
+// Should always be called, to initialize a fresh WebPAnimDecoderOptions
+// structure before modification. Returns false in case of version mismatch.
+// WebPAnimDecoderOptionsInit() must have succeeded before using the
+// 'dec_options' object.
+static WEBP_INLINE int WebPAnimDecoderOptionsInit(
+    WebPAnimDecoderOptions* dec_options) {
+  return WebPAnimDecoderOptionsInitInternal(dec_options,
+                                            WEBP_DEMUX_ABI_VERSION);
+}
+
+// Internal, version-checked, entry point.
+WEBP_EXTERN(WebPAnimDecoder*) WebPAnimDecoderNewInternal(
+    const WebPData*, const WebPAnimDecoderOptions*, int);
+
+// Creates and initializes a WebPAnimDecoder object.
+// Parameters:
+//   webp_data - (in) WebP bitstream. This should remain unchanged during the
+//                    lifetime of the output WebPAnimDecoder object.
+//   dec_options - (in) decoding options. Can be passed NULL to choose
+//                      reasonable defaults (in particular, color mode MODE_RGBA
+//                      will be picked).
+// Returns:
+//   A pointer to the newly created WebPAnimDecoder object, or NULL in case of
+//   parsing error, invalid option or memory error.
+static WEBP_INLINE WebPAnimDecoder* WebPAnimDecoderNew(
+    const WebPData* webp_data, const WebPAnimDecoderOptions* dec_options) {
+  return WebPAnimDecoderNewInternal(webp_data, dec_options,
+                                    WEBP_DEMUX_ABI_VERSION);
+}
+
+// Global information about the animation..
+struct WebPAnimInfo {
+  uint32_t canvas_width;
+  uint32_t canvas_height;
+  uint32_t loop_count;
+  uint32_t bgcolor;
+  uint32_t frame_count;
+  uint32_t pad[4];   // padding for later use
+};
+
+// Get global information about the animation.
+// Parameters:
+//   dec - (in) decoder instance to get information from.
+//   info - (out) global information fetched from the animation.
+// Returns:
+//   True on success.
+WEBP_EXTERN(int) WebPAnimDecoderGetInfo(const WebPAnimDecoder* dec,
+                                        WebPAnimInfo* info);
+
+// Fetch the next frame from 'dec' based on options supplied to
+// WebPAnimDecoderNew(). This will be a fully reconstructed canvas of size
+// 'canvas_width * 4 * canvas_height', and not just the frame sub-rectangle. The
+// returned buffer 'buf' is valid only until the next call to
+// WebPAnimDecoderGetNext(), WebPAnimDecoderReset() or WebPAnimDecoderDelete().
+// Parameters:
+//   dec - (in/out) decoder instance from which the next frame is to be fetched.
+//   buf - (out) decoded frame.
+//   timestamp - (out) timestamp of the frame in milliseconds.
+// Returns:
+//   False if any of the arguments are NULL, or if there is a parsing or
+//   decoding error, or if there are no more frames. Otherwise, returns true.
+WEBP_EXTERN(int) WebPAnimDecoderGetNext(WebPAnimDecoder* dec,
+                                        uint8_t** buf, int* timestamp);
+
+// Check if there are more frames left to decode.
+// Parameters:
+//   dec - (in) decoder instance to be checked.
+// Returns:
+//   True if 'dec' is not NULL and some frames are yet to be decoded.
+//   Otherwise, returns false.
+WEBP_EXTERN(int) WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder* dec);
+
+// Resets the WebPAnimDecoder object, so that next call to
+// WebPAnimDecoderGetNext() will restart decoding from 1st frame. This would be
+// helpful when all frames need to be decoded multiple times (e.g.
+// info.loop_count times) without destroying and recreating the 'dec' object.
+// Parameters:
+//   dec - (in/out) decoder instance to be reset
+WEBP_EXTERN(void) WebPAnimDecoderReset(WebPAnimDecoder* dec);
+
+// Grab the internal demuxer object.
+// Getting the demuxer object can be useful if one wants to use operations only
+// available through demuxer; e.g. to get XMP/EXIF/ICC metadata. The returned
+// demuxer object is owned by 'dec' and is valid only until the next call to
+// WebPAnimDecoderDelete().
+//
+// Parameters:
+//   dec - (in) decoder instance from which the demuxer object is to be fetched.
+WEBP_EXTERN(const WebPDemuxer*) WebPAnimDecoderGetDemuxer(
+    const WebPAnimDecoder* dec);
+
+// Deletes the WebPAnimDecoder object.
+// Parameters:
+//   dec - (in/out) decoder instance to be deleted
+WEBP_EXTERN(void) WebPAnimDecoderDelete(WebPAnimDecoder* dec);
+
+#ifdef __cplusplus
+}    // extern "C"
+#endif
+
+#endif  /* WEBP_WEBP_DEMUX_H_ */

+ 527 - 0
Vendor/WebP.framework/Headers/encode.h

@@ -0,0 +1,527 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+//   WebP encoder: main interface
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#ifndef WEBP_WEBP_ENCODE_H_
+#define WEBP_WEBP_ENCODE_H_
+
+#include "./types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define WEBP_ENCODER_ABI_VERSION 0x0209    // MAJOR(8b) + MINOR(8b)
+
+// Note: forward declaring enumerations is not allowed in (strict) C and C++,
+// the types are left here for reference.
+// typedef enum WebPImageHint WebPImageHint;
+// typedef enum WebPEncCSP WebPEncCSP;
+// typedef enum WebPPreset WebPPreset;
+// typedef enum WebPEncodingError WebPEncodingError;
+typedef struct WebPConfig WebPConfig;
+typedef struct WebPPicture WebPPicture;   // main structure for I/O
+typedef struct WebPAuxStats WebPAuxStats;
+typedef struct WebPMemoryWriter WebPMemoryWriter;
+
+// Return the encoder's version number, packed in hexadecimal using 8bits for
+// each of major/minor/revision. E.g: v2.5.7 is 0x020507.
+WEBP_EXTERN(int) WebPGetEncoderVersion(void);
+
+//------------------------------------------------------------------------------
+// One-stop-shop call! No questions asked:
+
+// Returns the size of the compressed data (pointed to by *output), or 0 if
+// an error occurred. The compressed data must be released by the caller
+// using the call 'WebPFree(*output)'.
+// These functions compress using the lossy format, and the quality_factor
+// can go from 0 (smaller output, lower quality) to 100 (best quality,
+// larger output).
+WEBP_EXTERN(size_t) WebPEncodeRGB(const uint8_t* rgb,
+                                  int width, int height, int stride,
+                                  float quality_factor, uint8_t** output);
+WEBP_EXTERN(size_t) WebPEncodeBGR(const uint8_t* bgr,
+                                  int width, int height, int stride,
+                                  float quality_factor, uint8_t** output);
+WEBP_EXTERN(size_t) WebPEncodeRGBA(const uint8_t* rgba,
+                                   int width, int height, int stride,
+                                   float quality_factor, uint8_t** output);
+WEBP_EXTERN(size_t) WebPEncodeBGRA(const uint8_t* bgra,
+                                   int width, int height, int stride,
+                                   float quality_factor, uint8_t** output);
+
+// These functions are the equivalent of the above, but compressing in a
+// lossless manner. Files are usually larger than lossy format, but will
+// not suffer any compression loss.
+WEBP_EXTERN(size_t) WebPEncodeLosslessRGB(const uint8_t* rgb,
+                                          int width, int height, int stride,
+                                          uint8_t** output);
+WEBP_EXTERN(size_t) WebPEncodeLosslessBGR(const uint8_t* bgr,
+                                          int width, int height, int stride,
+                                          uint8_t** output);
+WEBP_EXTERN(size_t) WebPEncodeLosslessRGBA(const uint8_t* rgba,
+                                           int width, int height, int stride,
+                                           uint8_t** output);
+WEBP_EXTERN(size_t) WebPEncodeLosslessBGRA(const uint8_t* bgra,
+                                           int width, int height, int stride,
+                                           uint8_t** output);
+
+// Releases memory returned by the WebPEncode*() functions above.
+WEBP_EXTERN(void) WebPFree(void* ptr);
+
+//------------------------------------------------------------------------------
+// Coding parameters
+
+// Image characteristics hint for the underlying encoder.
+typedef enum WebPImageHint {
+  WEBP_HINT_DEFAULT = 0,  // default preset.
+  WEBP_HINT_PICTURE,      // digital picture, like portrait, inner shot
+  WEBP_HINT_PHOTO,        // outdoor photograph, with natural lighting
+  WEBP_HINT_GRAPH,        // Discrete tone image (graph, map-tile etc).
+  WEBP_HINT_LAST
+} WebPImageHint;
+
+// Compression parameters.
+struct WebPConfig {
+  int lossless;           // Lossless encoding (0=lossy(default), 1=lossless).
+  float quality;          // between 0 (smallest file) and 100 (biggest)
+  int method;             // quality/speed trade-off (0=fast, 6=slower-better)
+
+  WebPImageHint image_hint;  // Hint for image type (lossless only for now).
+
+  // Parameters related to lossy compression only:
+  int target_size;        // if non-zero, set the desired target size in bytes.
+                          // Takes precedence over the 'compression' parameter.
+  float target_PSNR;      // if non-zero, specifies the minimal distortion to
+                          // try to achieve. Takes precedence over target_size.
+  int segments;           // maximum number of segments to use, in [1..4]
+  int sns_strength;       // Spatial Noise Shaping. 0=off, 100=maximum.
+  int filter_strength;    // range: [0 = off .. 100 = strongest]
+  int filter_sharpness;   // range: [0 = off .. 7 = least sharp]
+  int filter_type;        // filtering type: 0 = simple, 1 = strong (only used
+                          // if filter_strength > 0 or autofilter > 0)
+  int autofilter;         // Auto adjust filter's strength [0 = off, 1 = on]
+  int alpha_compression;  // Algorithm for encoding the alpha plane (0 = none,
+                          // 1 = compressed with WebP lossless). Default is 1.
+  int alpha_filtering;    // Predictive filtering method for alpha plane.
+                          //  0: none, 1: fast, 2: best. Default if 1.
+  int alpha_quality;      // Between 0 (smallest size) and 100 (lossless).
+                          // Default is 100.
+  int pass;               // number of entropy-analysis passes (in [1..10]).
+
+  int show_compressed;    // if true, export the compressed picture back.
+                          // In-loop filtering is not applied.
+  int preprocessing;      // preprocessing filter:
+                          // 0=none, 1=segment-smooth, 2=pseudo-random dithering
+  int partitions;         // log2(number of token partitions) in [0..3]. Default
+                          // is set to 0 for easier progressive decoding.
+  int partition_limit;    // quality degradation allowed to fit the 512k limit
+                          // on prediction modes coding (0: no degradation,
+                          // 100: maximum possible degradation).
+  int emulate_jpeg_size;  // If true, compression parameters will be remapped
+                          // to better match the expected output size from
+                          // JPEG compression. Generally, the output size will
+                          // be similar but the degradation will be lower.
+  int thread_level;       // If non-zero, try and use multi-threaded encoding.
+  int low_memory;         // If set, reduce memory usage (but increase CPU use).
+
+  int near_lossless;      // Near lossless encoding [0 = off(default) .. 100].
+                          // This feature is experimental.
+  int exact;              // if non-zero, preserve the exact RGB values under
+                          // transparent area. Otherwise, discard this invisible
+                          // RGB information for better compression. The default
+                          // value is 0.
+
+#ifdef WEBP_EXPERIMENTAL_FEATURES
+  int delta_palettization;
+  uint32_t pad[2];        // padding for later use
+#else
+  uint32_t pad[3];        // padding for later use
+#endif  // WEBP_EXPERIMENTAL_FEATURES
+};
+
+// Enumerate some predefined settings for WebPConfig, depending on the type
+// of source picture. These presets are used when calling WebPConfigPreset().
+typedef enum WebPPreset {
+  WEBP_PRESET_DEFAULT = 0,  // default preset.
+  WEBP_PRESET_PICTURE,      // digital picture, like portrait, inner shot
+  WEBP_PRESET_PHOTO,        // outdoor photograph, with natural lighting
+  WEBP_PRESET_DRAWING,      // hand or line drawing, with high-contrast details
+  WEBP_PRESET_ICON,         // small-sized colorful images
+  WEBP_PRESET_TEXT          // text-like
+} WebPPreset;
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(int) WebPConfigInitInternal(WebPConfig*, WebPPreset, float, int);
+
+// Should always be called, to initialize a fresh WebPConfig structure before
+// modification. Returns false in case of version mismatch. WebPConfigInit()
+// must have succeeded before using the 'config' object.
+// Note that the default values are lossless=0 and quality=75.
+static WEBP_INLINE int WebPConfigInit(WebPConfig* config) {
+  return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f,
+                                WEBP_ENCODER_ABI_VERSION);
+}
+
+// This function will initialize the configuration according to a predefined
+// set of parameters (referred to by 'preset') and a given quality factor.
+// This function can be called as a replacement to WebPConfigInit(). Will
+// return false in case of error.
+static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
+                                        WebPPreset preset, float quality) {
+  return WebPConfigInitInternal(config, preset, quality,
+                                WEBP_ENCODER_ABI_VERSION);
+}
+
+// Activate the lossless compression mode with the desired efficiency level
+// between 0 (fastest, lowest compression) and 9 (slower, best compression).
+// A good default level is '6', providing a fair tradeoff between compression
+// speed and final compressed size.
+// This function will overwrite several fields from config: 'method', 'quality'
+// and 'lossless'. Returns false in case of parameter error.
+WEBP_EXTERN(int) WebPConfigLosslessPreset(WebPConfig* config, int level);
+
+// Returns true if 'config' is non-NULL and all configuration parameters are
+// within their valid ranges.
+WEBP_EXTERN(int) WebPValidateConfig(const WebPConfig* config);
+
+//------------------------------------------------------------------------------
+// Input / Output
+// Structure for storing auxiliary statistics (mostly for lossy encoding).
+
+struct WebPAuxStats {
+  int coded_size;         // final size
+
+  float PSNR[5];          // peak-signal-to-noise ratio for Y/U/V/All/Alpha
+  int block_count[3];     // number of intra4/intra16/skipped macroblocks
+  int header_bytes[2];    // approximate number of bytes spent for header
+                          // and mode-partition #0
+  int residual_bytes[3][4];  // approximate number of bytes spent for
+                             // DC/AC/uv coefficients for each (0..3) segments.
+  int segment_size[4];    // number of macroblocks in each segments
+  int segment_quant[4];   // quantizer values for each segments
+  int segment_level[4];   // filtering strength for each segments [0..63]
+
+  int alpha_data_size;    // size of the transparency data
+  int layer_data_size;    // size of the enhancement layer data
+
+  // lossless encoder statistics
+  uint32_t lossless_features;  // bit0:predictor bit1:cross-color transform
+                               // bit2:subtract-green bit3:color indexing
+  int histogram_bits;          // number of precision bits of histogram
+  int transform_bits;          // precision bits for transform
+  int cache_bits;              // number of bits for color cache lookup
+  int palette_size;            // number of color in palette, if used
+  int lossless_size;           // final lossless size
+  int lossless_hdr_size;       // lossless header (transform, huffman etc) size
+  int lossless_data_size;      // lossless image data size
+
+  uint32_t pad[2];        // padding for later use
+};
+
+// Signature for output function. Should return true if writing was successful.
+// data/data_size is the segment of data to write, and 'picture' is for
+// reference (and so one can make use of picture->custom_ptr).
+typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size,
+                                  const WebPPicture* picture);
+
+// WebPMemoryWrite: a special WebPWriterFunction that writes to memory using
+// the following WebPMemoryWriter object (to be set as a custom_ptr).
+struct WebPMemoryWriter {
+  uint8_t* mem;       // final buffer (of size 'max_size', larger than 'size').
+  size_t   size;      // final size
+  size_t   max_size;  // total capacity
+  uint32_t pad[1];    // padding for later use
+};
+
+// The following must be called first before any use.
+WEBP_EXTERN(void) WebPMemoryWriterInit(WebPMemoryWriter* writer);
+
+// The following must be called to deallocate writer->mem memory. The 'writer'
+// object itself is not deallocated.
+WEBP_EXTERN(void) WebPMemoryWriterClear(WebPMemoryWriter* writer);
+// The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon
+// completion, writer.mem and writer.size will hold the coded data.
+// writer.mem must be freed by calling WebPMemoryWriterClear.
+WEBP_EXTERN(int) WebPMemoryWrite(const uint8_t* data, size_t data_size,
+                                 const WebPPicture* picture);
+
+// Progress hook, called from time to time to report progress. It can return
+// false to request an abort of the encoding process, or true otherwise if
+// everything is OK.
+typedef int (*WebPProgressHook)(int percent, const WebPPicture* picture);
+
+// Color spaces.
+typedef enum WebPEncCSP {
+  // chroma sampling
+  WEBP_YUV420  = 0,        // 4:2:0
+  WEBP_YUV420A = 4,        // alpha channel variant
+  WEBP_CSP_UV_MASK = 3,    // bit-mask to get the UV sampling factors
+  WEBP_CSP_ALPHA_BIT = 4   // bit that is set if alpha is present
+} WebPEncCSP;
+
+// Encoding error conditions.
+typedef enum WebPEncodingError {
+  VP8_ENC_OK = 0,
+  VP8_ENC_ERROR_OUT_OF_MEMORY,            // memory error allocating objects
+  VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY,  // memory error while flushing bits
+  VP8_ENC_ERROR_NULL_PARAMETER,           // a pointer parameter is NULL
+  VP8_ENC_ERROR_INVALID_CONFIGURATION,    // configuration is invalid
+  VP8_ENC_ERROR_BAD_DIMENSION,            // picture has invalid width/height
+  VP8_ENC_ERROR_PARTITION0_OVERFLOW,      // partition is bigger than 512k
+  VP8_ENC_ERROR_PARTITION_OVERFLOW,       // partition is bigger than 16M
+  VP8_ENC_ERROR_BAD_WRITE,                // error while flushing bytes
+  VP8_ENC_ERROR_FILE_TOO_BIG,             // file is bigger than 4G
+  VP8_ENC_ERROR_USER_ABORT,               // abort request by user
+  VP8_ENC_ERROR_LAST                      // list terminator. always last.
+} WebPEncodingError;
+
+// maximum width/height allowed (inclusive), in pixels
+#define WEBP_MAX_DIMENSION 16383
+
+// Main exchange structure (input samples, output bytes, statistics)
+struct WebPPicture {
+  //   INPUT
+  //////////////
+  // Main flag for encoder selecting between ARGB or YUV input.
+  // It is recommended to use ARGB input (*argb, argb_stride) for lossless
+  // compression, and YUV input (*y, *u, *v, etc.) for lossy compression
+  // since these are the respective native colorspace for these formats.
+  int use_argb;
+
+  // YUV input (mostly used for input to lossy compression)
+  WebPEncCSP colorspace;     // colorspace: should be YUV420 for now (=Y'CbCr).
+  int width, height;         // dimensions (less or equal to WEBP_MAX_DIMENSION)
+  uint8_t *y, *u, *v;        // pointers to luma/chroma planes.
+  int y_stride, uv_stride;   // luma/chroma strides.
+  uint8_t* a;                // pointer to the alpha plane
+  int a_stride;              // stride of the alpha plane
+  uint32_t pad1[2];          // padding for later use
+
+  // ARGB input (mostly used for input to lossless compression)
+  uint32_t* argb;            // Pointer to argb (32 bit) plane.
+  int argb_stride;           // This is stride in pixels units, not bytes.
+  uint32_t pad2[3];          // padding for later use
+
+  //   OUTPUT
+  ///////////////
+  // Byte-emission hook, to store compressed bytes as they are ready.
+  WebPWriterFunction writer;  // can be NULL
+  void* custom_ptr;           // can be used by the writer.
+
+  // map for extra information (only for lossy compression mode)
+  int extra_info_type;    // 1: intra type, 2: segment, 3: quant
+                          // 4: intra-16 prediction mode,
+                          // 5: chroma prediction mode,
+                          // 6: bit cost, 7: distortion
+  uint8_t* extra_info;    // if not NULL, points to an array of size
+                          // ((width + 15) / 16) * ((height + 15) / 16) that
+                          // will be filled with a macroblock map, depending
+                          // on extra_info_type.
+
+  //   STATS AND REPORTS
+  ///////////////////////////
+  // Pointer to side statistics (updated only if not NULL)
+  WebPAuxStats* stats;
+
+  // Error code for the latest error encountered during encoding
+  WebPEncodingError error_code;
+
+  // If not NULL, report progress during encoding.
+  WebPProgressHook progress_hook;
+
+  void* user_data;        // this field is free to be set to any value and
+                          // used during callbacks (like progress-report e.g.).
+
+  uint32_t pad3[3];       // padding for later use
+
+  // Unused for now
+  uint8_t *pad4, *pad5;
+  uint32_t pad6[8];       // padding for later use
+
+  // PRIVATE FIELDS
+  ////////////////////
+  void* memory_;          // row chunk of memory for yuva planes
+  void* memory_argb_;     // and for argb too.
+  void* pad7[2];          // padding for later use
+};
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(int) WebPPictureInitInternal(WebPPicture*, int);
+
+// Should always be called, to initialize the structure. Returns false in case
+// of version mismatch. WebPPictureInit() must have succeeded before using the
+// 'picture' object.
+// Note that, by default, use_argb is false and colorspace is WEBP_YUV420.
+static WEBP_INLINE int WebPPictureInit(WebPPicture* picture) {
+  return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION);
+}
+
+//------------------------------------------------------------------------------
+// WebPPicture utils
+
+// Convenience allocation / deallocation based on picture->width/height:
+// Allocate y/u/v buffers as per colorspace/width/height specification.
+// Note! This function will free the previous buffer if needed.
+// Returns false in case of memory error.
+WEBP_EXTERN(int) WebPPictureAlloc(WebPPicture* picture);
+
+// Release the memory allocated by WebPPictureAlloc() or WebPPictureImport*().
+// Note that this function does _not_ free the memory used by the 'picture'
+// object itself.
+// Besides memory (which is reclaimed) all other fields of 'picture' are
+// preserved.
+WEBP_EXTERN(void) WebPPictureFree(WebPPicture* picture);
+
+// Copy the pixels of *src into *dst, using WebPPictureAlloc. Upon return, *dst
+// will fully own the copied pixels (this is not a view). The 'dst' picture need
+// not be initialized as its content is overwritten.
+// Returns false in case of memory allocation error.
+WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* src, WebPPicture* dst);
+
+// Compute PSNR, SSIM or LSIM distortion metric between two pictures. Results
+// are in dB, stored in result[] in the Y/U/V/Alpha/All or B/G/R/A/All order.
+// Returns false in case of error (src and ref don't have same dimension, ...)
+// Warning: this function is rather CPU-intensive.
+WEBP_EXTERN(int) WebPPictureDistortion(
+    const WebPPicture* src, const WebPPicture* ref,
+    int metric_type,           // 0 = PSNR, 1 = SSIM, 2 = LSIM
+    float result[5]);
+
+// self-crops a picture to the rectangle defined by top/left/width/height.
+// Returns false in case of memory allocation error, or if the rectangle is
+// outside of the source picture.
+// The rectangle for the view is defined by the top-left corner pixel
+// coordinates (left, top) as well as its width and height. This rectangle
+// must be fully be comprised inside the 'src' source picture. If the source
+// picture uses the YUV420 colorspace, the top and left coordinates will be
+// snapped to even values.
+WEBP_EXTERN(int) WebPPictureCrop(WebPPicture* picture,
+                                 int left, int top, int width, int height);
+
+// Extracts a view from 'src' picture into 'dst'. The rectangle for the view
+// is defined by the top-left corner pixel coordinates (left, top) as well
+// as its width and height. This rectangle must be fully be comprised inside
+// the 'src' source picture. If the source picture uses the YUV420 colorspace,
+// the top and left coordinates will be snapped to even values.
+// Picture 'src' must out-live 'dst' picture. Self-extraction of view is allowed
+// ('src' equal to 'dst') as a mean of fast-cropping (but note that doing so,
+// the original dimension will be lost). Picture 'dst' need not be initialized
+// with WebPPictureInit() if it is different from 'src', since its content will
+// be overwritten.
+// Returns false in case of memory allocation error or invalid parameters.
+WEBP_EXTERN(int) WebPPictureView(const WebPPicture* src,
+                                 int left, int top, int width, int height,
+                                 WebPPicture* dst);
+
+// Returns true if the 'picture' is actually a view and therefore does
+// not own the memory for pixels.
+WEBP_EXTERN(int) WebPPictureIsView(const WebPPicture* picture);
+
+// Rescale a picture to new dimension width x height.
+// If either 'width' or 'height' (but not both) is 0 the corresponding
+// dimension will be calculated preserving the aspect ratio.
+// No gamma correction is applied.
+// Returns false in case of error (invalid parameter or insufficient memory).
+WEBP_EXTERN(int) WebPPictureRescale(WebPPicture* pic, int width, int height);
+
+// Colorspace conversion function to import RGB samples.
+// Previous buffer will be free'd, if any.
+// *rgb buffer should have a size of at least height * rgb_stride.
+// Returns false in case of memory error.
+WEBP_EXTERN(int) WebPPictureImportRGB(
+    WebPPicture* picture, const uint8_t* rgb, int rgb_stride);
+// Same, but for RGBA buffer.
+WEBP_EXTERN(int) WebPPictureImportRGBA(
+    WebPPicture* picture, const uint8_t* rgba, int rgba_stride);
+// Same, but for RGBA buffer. Imports the RGB direct from the 32-bit format
+// input buffer ignoring the alpha channel. Avoids needing to copy the data
+// to a temporary 24-bit RGB buffer to import the RGB only.
+WEBP_EXTERN(int) WebPPictureImportRGBX(
+    WebPPicture* picture, const uint8_t* rgbx, int rgbx_stride);
+
+// Variants of the above, but taking BGR(A|X) input.
+WEBP_EXTERN(int) WebPPictureImportBGR(
+    WebPPicture* picture, const uint8_t* bgr, int bgr_stride);
+WEBP_EXTERN(int) WebPPictureImportBGRA(
+    WebPPicture* picture, const uint8_t* bgra, int bgra_stride);
+WEBP_EXTERN(int) WebPPictureImportBGRX(
+    WebPPicture* picture, const uint8_t* bgrx, int bgrx_stride);
+
+// Converts picture->argb data to the YUV420A format. The 'colorspace'
+// parameter is deprecated and should be equal to WEBP_YUV420.
+// Upon return, picture->use_argb is set to false. The presence of real
+// non-opaque transparent values is detected, and 'colorspace' will be
+// adjusted accordingly. Note that this method is lossy.
+// Returns false in case of error.
+WEBP_EXTERN(int) WebPPictureARGBToYUVA(WebPPicture* picture,
+                                       WebPEncCSP /*colorspace = WEBP_YUV420*/);
+
+// Same as WebPPictureARGBToYUVA(), but the conversion is done using
+// pseudo-random dithering with a strength 'dithering' between
+// 0.0 (no dithering) and 1.0 (maximum dithering). This is useful
+// for photographic picture.
+WEBP_EXTERN(int) WebPPictureARGBToYUVADithered(
+    WebPPicture* picture, WebPEncCSP colorspace, float dithering);
+
+// Performs 'smart' RGBA->YUVA420 downsampling and colorspace conversion.
+// Downsampling is handled with extra care in case of color clipping. This
+// method is roughly 2x slower than WebPPictureARGBToYUVA() but produces better
+// YUV representation.
+// Returns false in case of error.
+WEBP_EXTERN(int) WebPPictureSmartARGBToYUVA(WebPPicture* picture);
+
+// Converts picture->yuv to picture->argb and sets picture->use_argb to true.
+// The input format must be YUV_420 or YUV_420A.
+// Note that the use of this method is discouraged if one has access to the
+// raw ARGB samples, since using YUV420 is comparatively lossy. Also, the
+// conversion from YUV420 to ARGB incurs a small loss too.
+// Returns false in case of error.
+WEBP_EXTERN(int) WebPPictureYUVAToARGB(WebPPicture* picture);
+
+// Helper function: given a width x height plane of RGBA or YUV(A) samples
+// clean-up the YUV or RGB samples under fully transparent area, to help
+// compressibility (no guarantee, though).
+WEBP_EXTERN(void) WebPCleanupTransparentArea(WebPPicture* picture);
+
+// Scan the picture 'picture' for the presence of non fully opaque alpha values.
+// Returns true in such case. Otherwise returns false (indicating that the
+// alpha plane can be ignored altogether e.g.).
+WEBP_EXTERN(int) WebPPictureHasTransparency(const WebPPicture* picture);
+
+// Remove the transparency information (if present) by blending the color with
+// the background color 'background_rgb' (specified as 24bit RGB triplet).
+// After this call, all alpha values are reset to 0xff.
+WEBP_EXTERN(void) WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb);
+
+//------------------------------------------------------------------------------
+// Main call
+
+// Main encoding call, after config and picture have been initialized.
+// 'picture' must be less than 16384x16384 in dimension (cf WEBP_MAX_DIMENSION),
+// and the 'config' object must be a valid one.
+// Returns false in case of error, true otherwise.
+// In case of error, picture->error_code is updated accordingly.
+// 'picture' can hold the source samples in both YUV(A) or ARGB input, depending
+// on the value of 'picture->use_argb'. It is highly recommended to use
+// the former for lossy encoding, and the latter for lossless encoding
+// (when config.lossless is true). Automatic conversion from one format to
+// another is provided but they both incur some loss.
+WEBP_EXTERN(int) WebPEncode(const WebPConfig* config, WebPPicture* picture);
+
+//------------------------------------------------------------------------------
+
+#ifdef __cplusplus
+}    // extern "C"
+#endif
+
+#endif  /* WEBP_WEBP_ENCODE_H_ */

+ 51 - 0
Vendor/WebP.framework/Headers/extras.h

@@ -0,0 +1,51 @@
+// Copyright 2015 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+
+#ifndef WEBP_WEBP_EXTRAS_H_
+#define WEBP_WEBP_EXTRAS_H_
+
+#include "./types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "./encode.h"
+
+#define WEBP_EXTRAS_ABI_VERSION 0x0000    // MAJOR(8b) + MINOR(8b)
+
+//------------------------------------------------------------------------------
+
+// Returns the version number of the extras library, packed in hexadecimal using
+// 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
+WEBP_EXTERN(int) WebPGetExtrasVersion(void);
+
+//------------------------------------------------------------------------------
+// Ad-hoc colorspace importers.
+
+// Import luma sample (gray scale image) into 'picture'. The 'picture'
+// width and height must be set prior to calling this function.
+WEBP_EXTERN(int) WebPImportGray(const uint8_t* gray, WebPPicture* picture);
+
+// Import rgb sample in RGB565 packed format into 'picture'. The 'picture'
+// width and height must be set prior to calling this function.
+WEBP_EXTERN(int) WebPImportRGB565(const uint8_t* rgb565, WebPPicture* pic);
+
+// Import rgb sample in RGB4444 packed format into 'picture'. The 'picture'
+// width and height must be set prior to calling this function.
+WEBP_EXTERN(int) WebPImportRGB4444(const uint8_t* rgb4444, WebPPicture* pic);
+
+//------------------------------------------------------------------------------
+
+#ifdef __cplusplus
+}    // extern "C"
+#endif
+
+#endif  /* WEBP_WEBP_EXTRAS_H_ */

+ 88 - 0
Vendor/WebP.framework/Headers/format_constants.h

@@ -0,0 +1,88 @@
+// Copyright 2012 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+//  Internal header for constants related to WebP file format.
+//
+// Author: Urvang (urvang@google.com)
+
+#ifndef WEBP_WEBP_FORMAT_CONSTANTS_H_
+#define WEBP_WEBP_FORMAT_CONSTANTS_H_
+
+// Create fourcc of the chunk from the chunk tag characters.
+#define MKFOURCC(a, b, c, d) ((a) | (b) << 8 | (c) << 16 | (uint32_t)(d) << 24)
+
+// VP8 related constants.
+#define VP8_SIGNATURE 0x9d012a              // Signature in VP8 data.
+#define VP8_MAX_PARTITION0_SIZE (1 << 19)   // max size of mode partition
+#define VP8_MAX_PARTITION_SIZE  (1 << 24)   // max size for token partition
+#define VP8_FRAME_HEADER_SIZE 10  // Size of the frame header within VP8 data.
+
+// VP8L related constants.
+#define VP8L_SIGNATURE_SIZE          1      // VP8L signature size.
+#define VP8L_MAGIC_BYTE              0x2f   // VP8L signature byte.
+#define VP8L_IMAGE_SIZE_BITS         14     // Number of bits used to store
+                                            // width and height.
+#define VP8L_VERSION_BITS            3      // 3 bits reserved for version.
+#define VP8L_VERSION                 0      // version 0
+#define VP8L_FRAME_HEADER_SIZE       5      // Size of the VP8L frame header.
+
+#define MAX_PALETTE_SIZE             256
+#define MAX_CACHE_BITS               11
+#define HUFFMAN_CODES_PER_META_CODE  5
+#define ARGB_BLACK                   0xff000000
+
+#define DEFAULT_CODE_LENGTH          8
+#define MAX_ALLOWED_CODE_LENGTH      15
+
+#define NUM_LITERAL_CODES            256
+#define NUM_LENGTH_CODES             24
+#define NUM_DISTANCE_CODES           40
+#define CODE_LENGTH_CODES            19
+
+#define MIN_HUFFMAN_BITS             2  // min number of Huffman bits
+#define MAX_HUFFMAN_BITS             9  // max number of Huffman bits
+
+#define TRANSFORM_PRESENT            1  // The bit to be written when next data
+                                        // to be read is a transform.
+#define NUM_TRANSFORMS               4  // Maximum number of allowed transform
+                                        // in a bitstream.
+typedef enum {
+  PREDICTOR_TRANSFORM      = 0,
+  CROSS_COLOR_TRANSFORM    = 1,
+  SUBTRACT_GREEN           = 2,
+  COLOR_INDEXING_TRANSFORM = 3
+} VP8LImageTransformType;
+
+// Alpha related constants.
+#define ALPHA_HEADER_LEN            1
+#define ALPHA_NO_COMPRESSION        0
+#define ALPHA_LOSSLESS_COMPRESSION  1
+#define ALPHA_PREPROCESSED_LEVELS   1
+
+// Mux related constants.
+#define TAG_SIZE           4     // Size of a chunk tag (e.g. "VP8L").
+#define CHUNK_SIZE_BYTES   4     // Size needed to store chunk's size.
+#define CHUNK_HEADER_SIZE  8     // Size of a chunk header.
+#define RIFF_HEADER_SIZE   12    // Size of the RIFF header ("RIFFnnnnWEBP").
+#define ANMF_CHUNK_SIZE    16    // Size of an ANMF chunk.
+#define ANIM_CHUNK_SIZE    6     // Size of an ANIM chunk.
+#define FRGM_CHUNK_SIZE    6     // Size of a FRGM chunk.
+#define VP8X_CHUNK_SIZE    10    // Size of a VP8X chunk.
+
+#define MAX_CANVAS_SIZE     (1 << 24)     // 24-bit max for VP8X width/height.
+#define MAX_IMAGE_AREA      (1ULL << 32)  // 32-bit max for width x height.
+#define MAX_LOOP_COUNT      (1 << 16)     // maximum value for loop-count
+#define MAX_DURATION        (1 << 24)     // maximum duration
+#define MAX_POSITION_OFFSET (1 << 24)     // maximum frame/fragment x/y offset
+
+// Maximum chunk payload is such that adding the header and padding won't
+// overflow a uint32_t.
+#define MAX_CHUNK_PAYLOAD (~0U - CHUNK_HEADER_SIZE - 1)
+
+#endif  /* WEBP_WEBP_FORMAT_CONSTANTS_H_ */

+ 530 - 0
Vendor/WebP.framework/Headers/mux.h

@@ -0,0 +1,530 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+//  RIFF container manipulation and encoding for WebP images.
+//
+// Authors: Urvang (urvang@google.com)
+//          Vikas (vikasa@google.com)
+
+#ifndef WEBP_WEBP_MUX_H_
+#define WEBP_WEBP_MUX_H_
+
+#include "./mux_types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define WEBP_MUX_ABI_VERSION 0x0106        // MAJOR(8b) + MINOR(8b)
+
+//------------------------------------------------------------------------------
+// Mux API
+//
+// This API allows manipulation of WebP container images containing features
+// like color profile, metadata, animation and fragmented images.
+//
+// Code Example#1: Create a WebPMux object with image data, color profile and
+// XMP metadata.
+/*
+  int copy_data = 0;
+  WebPMux* mux = WebPMuxNew();
+  // ... (Prepare image data).
+  WebPMuxSetImage(mux, &image, copy_data);
+  // ... (Prepare ICCP color profile data).
+  WebPMuxSetChunk(mux, "ICCP", &icc_profile, copy_data);
+  // ... (Prepare XMP metadata).
+  WebPMuxSetChunk(mux, "XMP ", &xmp, copy_data);
+  // Get data from mux in WebP RIFF format.
+  WebPMuxAssemble(mux, &output_data);
+  WebPMuxDelete(mux);
+  // ... (Consume output_data; e.g. write output_data.bytes to file).
+  WebPDataClear(&output_data);
+*/
+
+// Code Example#2: Get image and color profile data from a WebP file.
+/*
+  int copy_data = 0;
+  // ... (Read data from file).
+  WebPMux* mux = WebPMuxCreate(&data, copy_data);
+  WebPMuxGetFrame(mux, 1, &image);
+  // ... (Consume image; e.g. call WebPDecode() to decode the data).
+  WebPMuxGetChunk(mux, "ICCP", &icc_profile);
+  // ... (Consume icc_data).
+  WebPMuxDelete(mux);
+  free(data);
+*/
+
+// Note: forward declaring enumerations is not allowed in (strict) C and C++,
+// the types are left here for reference.
+// typedef enum WebPMuxError WebPMuxError;
+// typedef enum WebPChunkId WebPChunkId;
+typedef struct WebPMux WebPMux;   // main opaque object.
+typedef struct WebPMuxFrameInfo WebPMuxFrameInfo;
+typedef struct WebPMuxAnimParams WebPMuxAnimParams;
+typedef struct WebPAnimEncoderOptions WebPAnimEncoderOptions;
+
+// Error codes
+typedef enum WebPMuxError {
+  WEBP_MUX_OK                 =  1,
+  WEBP_MUX_NOT_FOUND          =  0,
+  WEBP_MUX_INVALID_ARGUMENT   = -1,
+  WEBP_MUX_BAD_DATA           = -2,
+  WEBP_MUX_MEMORY_ERROR       = -3,
+  WEBP_MUX_NOT_ENOUGH_DATA    = -4
+} WebPMuxError;
+
+// IDs for different types of chunks.
+typedef enum WebPChunkId {
+  WEBP_CHUNK_VP8X,     // VP8X
+  WEBP_CHUNK_ICCP,     // ICCP
+  WEBP_CHUNK_ANIM,     // ANIM
+  WEBP_CHUNK_ANMF,     // ANMF
+  WEBP_CHUNK_FRGM,     // FRGM
+  WEBP_CHUNK_ALPHA,    // ALPH
+  WEBP_CHUNK_IMAGE,    // VP8/VP8L
+  WEBP_CHUNK_EXIF,     // EXIF
+  WEBP_CHUNK_XMP,      // XMP
+  WEBP_CHUNK_UNKNOWN,  // Other chunks.
+  WEBP_CHUNK_NIL
+} WebPChunkId;
+
+//------------------------------------------------------------------------------
+
+// Returns the version number of the mux library, packed in hexadecimal using
+// 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
+WEBP_EXTERN(int) WebPGetMuxVersion(void);
+
+//------------------------------------------------------------------------------
+// Life of a Mux object
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(WebPMux*) WebPNewInternal(int);
+
+// Creates an empty mux object.
+// Returns:
+//   A pointer to the newly created empty mux object.
+//   Or NULL in case of memory error.
+static WEBP_INLINE WebPMux* WebPMuxNew(void) {
+  return WebPNewInternal(WEBP_MUX_ABI_VERSION);
+}
+
+// Deletes the mux object.
+// Parameters:
+//   mux - (in/out) object to be deleted
+WEBP_EXTERN(void) WebPMuxDelete(WebPMux* mux);
+
+//------------------------------------------------------------------------------
+// Mux creation.
+
+// Internal, version-checked, entry point
+WEBP_EXTERN(WebPMux*) WebPMuxCreateInternal(const WebPData*, int, int);
+
+// Creates a mux object from raw data given in WebP RIFF format.
+// Parameters:
+//   bitstream - (in) the bitstream data in WebP RIFF format
+//   copy_data - (in) value 1 indicates given data WILL be copied to the mux
+//               object and value 0 indicates data will NOT be copied.
+// Returns:
+//   A pointer to the mux object created from given data - on success.
+//   NULL - In case of invalid data or memory error.
+static WEBP_INLINE WebPMux* WebPMuxCreate(const WebPData* bitstream,
+                                          int copy_data) {
+  return WebPMuxCreateInternal(bitstream, copy_data, WEBP_MUX_ABI_VERSION);
+}
+
+//------------------------------------------------------------------------------
+// Non-image chunks.
+
+// Note: Only non-image related chunks should be managed through chunk APIs.
+// (Image related chunks are: "ANMF", "FRGM", "VP8 ", "VP8L" and "ALPH").
+// To add, get and delete images, use WebPMuxSetImage(), WebPMuxPushFrame(),
+// WebPMuxGetFrame() and WebPMuxDeleteFrame().
+
+// Adds a chunk with id 'fourcc' and data 'chunk_data' in the mux object.
+// Any existing chunk(s) with the same id will be removed.
+// Parameters:
+//   mux - (in/out) object to which the chunk is to be added
+//   fourcc - (in) a character array containing the fourcc of the given chunk;
+//                 e.g., "ICCP", "XMP ", "EXIF" etc.
+//   chunk_data - (in) the chunk data to be added
+//   copy_data - (in) value 1 indicates given data WILL be copied to the mux
+//               object and value 0 indicates data will NOT be copied.
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux, fourcc or chunk_data is NULL
+//                               or if fourcc corresponds to an image chunk.
+//   WEBP_MUX_MEMORY_ERROR - on memory allocation error.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxSetChunk(
+    WebPMux* mux, const char fourcc[4], const WebPData* chunk_data,
+    int copy_data);
+
+// Gets a reference to the data of the chunk with id 'fourcc' in the mux object.
+// The caller should NOT free the returned data.
+// Parameters:
+//   mux - (in) object from which the chunk data is to be fetched
+//   fourcc - (in) a character array containing the fourcc of the chunk;
+//                 e.g., "ICCP", "XMP ", "EXIF" etc.
+//   chunk_data - (out) returned chunk data
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux, fourcc or chunk_data is NULL
+//                               or if fourcc corresponds to an image chunk.
+//   WEBP_MUX_NOT_FOUND - If mux does not contain a chunk with the given id.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxGetChunk(
+    const WebPMux* mux, const char fourcc[4], WebPData* chunk_data);
+
+// Deletes the chunk with the given 'fourcc' from the mux object.
+// Parameters:
+//   mux - (in/out) object from which the chunk is to be deleted
+//   fourcc - (in) a character array containing the fourcc of the chunk;
+//                 e.g., "ICCP", "XMP ", "EXIF" etc.
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux or fourcc is NULL
+//                               or if fourcc corresponds to an image chunk.
+//   WEBP_MUX_NOT_FOUND - If mux does not contain a chunk with the given fourcc.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxDeleteChunk(
+    WebPMux* mux, const char fourcc[4]);
+
+//------------------------------------------------------------------------------
+// Images.
+
+// Encapsulates data about a single frame/fragment.
+struct WebPMuxFrameInfo {
+  WebPData    bitstream;  // image data: can be a raw VP8/VP8L bitstream
+                          // or a single-image WebP file.
+  int         x_offset;   // x-offset of the frame.
+  int         y_offset;   // y-offset of the frame.
+  int         duration;   // duration of the frame (in milliseconds).
+
+  WebPChunkId id;         // frame type: should be one of WEBP_CHUNK_ANMF,
+                          // WEBP_CHUNK_FRGM or WEBP_CHUNK_IMAGE
+  WebPMuxAnimDispose dispose_method;  // Disposal method for the frame.
+  WebPMuxAnimBlend   blend_method;    // Blend operation for the frame.
+  uint32_t    pad[1];     // padding for later use
+};
+
+// Sets the (non-animated and non-fragmented) image in the mux object.
+// Note: Any existing images (including frames/fragments) will be removed.
+// Parameters:
+//   mux - (in/out) object in which the image is to be set
+//   bitstream - (in) can be a raw VP8/VP8L bitstream or a single-image
+//               WebP file (non-animated and non-fragmented)
+//   copy_data - (in) value 1 indicates given data WILL be copied to the mux
+//               object and value 0 indicates data will NOT be copied.
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux is NULL or bitstream is NULL.
+//   WEBP_MUX_MEMORY_ERROR - on memory allocation error.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxSetImage(
+    WebPMux* mux, const WebPData* bitstream, int copy_data);
+
+// Adds a frame at the end of the mux object.
+// Notes: (1) frame.id should be one of WEBP_CHUNK_ANMF or WEBP_CHUNK_FRGM
+//        (2) For setting a non-animated non-fragmented image, use
+//            WebPMuxSetImage() instead.
+//        (3) Type of frame being pushed must be same as the frames in mux.
+//        (4) As WebP only supports even offsets, any odd offset will be snapped
+//            to an even location using: offset &= ~1
+// Parameters:
+//   mux - (in/out) object to which the frame is to be added
+//   frame - (in) frame data.
+//   copy_data - (in) value 1 indicates given data WILL be copied to the mux
+//               object and value 0 indicates data will NOT be copied.
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux or frame is NULL
+//                               or if content of 'frame' is invalid.
+//   WEBP_MUX_MEMORY_ERROR - on memory allocation error.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxPushFrame(
+    WebPMux* mux, const WebPMuxFrameInfo* frame, int copy_data);
+
+// Gets the nth frame from the mux object.
+// The content of 'frame->bitstream' is allocated using malloc(), and NOT
+// owned by the 'mux' object. It MUST be deallocated by the caller by calling
+// WebPDataClear().
+// nth=0 has a special meaning - last position.
+// Parameters:
+//   mux - (in) object from which the info is to be fetched
+//   nth - (in) index of the frame in the mux object
+//   frame - (out) data of the returned frame
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux or frame is NULL.
+//   WEBP_MUX_NOT_FOUND - if there are less than nth frames in the mux object.
+//   WEBP_MUX_BAD_DATA - if nth frame chunk in mux is invalid.
+//   WEBP_MUX_MEMORY_ERROR - on memory allocation error.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxGetFrame(
+    const WebPMux* mux, uint32_t nth, WebPMuxFrameInfo* frame);
+
+// Deletes a frame from the mux object.
+// nth=0 has a special meaning - last position.
+// Parameters:
+//   mux - (in/out) object from which a frame is to be deleted
+//   nth - (in) The position from which the frame is to be deleted
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux is NULL.
+//   WEBP_MUX_NOT_FOUND - If there are less than nth frames in the mux object
+//                        before deletion.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxDeleteFrame(WebPMux* mux, uint32_t nth);
+
+//------------------------------------------------------------------------------
+// Animation.
+
+// Animation parameters.
+struct WebPMuxAnimParams {
+  uint32_t bgcolor;  // Background color of the canvas stored (in MSB order) as:
+                     // Bits 00 to 07: Alpha.
+                     // Bits 08 to 15: Red.
+                     // Bits 16 to 23: Green.
+                     // Bits 24 to 31: Blue.
+  int loop_count;    // Number of times to repeat the animation [0 = infinite].
+};
+
+// Sets the animation parameters in the mux object. Any existing ANIM chunks
+// will be removed.
+// Parameters:
+//   mux - (in/out) object in which ANIM chunk is to be set/added
+//   params - (in) animation parameters.
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux or params is NULL.
+//   WEBP_MUX_MEMORY_ERROR - on memory allocation error.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxSetAnimationParams(
+    WebPMux* mux, const WebPMuxAnimParams* params);
+
+// Gets the animation parameters from the mux object.
+// Parameters:
+//   mux - (in) object from which the animation parameters to be fetched
+//   params - (out) animation parameters extracted from the ANIM chunk
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux or params is NULL.
+//   WEBP_MUX_NOT_FOUND - if ANIM chunk is not present in mux object.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxGetAnimationParams(
+    const WebPMux* mux, WebPMuxAnimParams* params);
+
+//------------------------------------------------------------------------------
+// Misc Utilities.
+
+// Sets the canvas size for the mux object. The width and height can be
+// specified explicitly or left as zero (0, 0).
+// * When width and height are specified explicitly, then this frame bound is
+//   enforced during subsequent calls to WebPMuxAssemble() and an error is
+//   reported if any animated frame does not completely fit within the canvas.
+// * When unspecified (0, 0), the constructed canvas will get the frame bounds
+//   from the bounding-box over all frames after calling WebPMuxAssemble().
+// Parameters:
+//   mux - (in) object to which the canvas size is to be set
+//   width - (in) canvas width
+//   height - (in) canvas height
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux is NULL; or
+//                               width or height are invalid or out of bounds
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxSetCanvasSize(WebPMux* mux,
+                                               int width, int height);
+
+// Gets the canvas size from the mux object.
+// Note: This method assumes that the VP8X chunk, if present, is up-to-date.
+// That is, the mux object hasn't been modified since the last call to
+// WebPMuxAssemble() or WebPMuxCreate().
+// Parameters:
+//   mux - (in) object from which the canvas size is to be fetched
+//   width - (out) canvas width
+//   height - (out) canvas height
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux, width or height is NULL.
+//   WEBP_MUX_BAD_DATA - if VP8X/VP8/VP8L chunk or canvas size is invalid.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxGetCanvasSize(const WebPMux* mux,
+                                               int* width, int* height);
+
+// Gets the feature flags from the mux object.
+// Note: This method assumes that the VP8X chunk, if present, is up-to-date.
+// That is, the mux object hasn't been modified since the last call to
+// WebPMuxAssemble() or WebPMuxCreate().
+// Parameters:
+//   mux - (in) object from which the features are to be fetched
+//   flags - (out) the flags specifying which features are present in the
+//           mux object. This will be an OR of various flag values.
+//           Enum 'WebPFeatureFlags' can be used to test individual flag values.
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux or flags is NULL.
+//   WEBP_MUX_BAD_DATA - if VP8X/VP8/VP8L chunk or canvas size is invalid.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxGetFeatures(const WebPMux* mux,
+                                             uint32_t* flags);
+
+// Gets number of chunks with the given 'id' in the mux object.
+// Parameters:
+//   mux - (in) object from which the info is to be fetched
+//   id - (in) chunk id specifying the type of chunk
+//   num_elements - (out) number of chunks with the given chunk id
+// Returns:
+//   WEBP_MUX_INVALID_ARGUMENT - if mux, or num_elements is NULL.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxNumChunks(const WebPMux* mux,
+                                           WebPChunkId id, int* num_elements);
+
+// Assembles all chunks in WebP RIFF format and returns in 'assembled_data'.
+// This function also validates the mux object.
+// Note: The content of 'assembled_data' will be ignored and overwritten.
+// Also, the content of 'assembled_data' is allocated using malloc(), and NOT
+// owned by the 'mux' object. It MUST be deallocated by the caller by calling
+// WebPDataClear(). It's always safe to call WebPDataClear() upon return,
+// even in case of error.
+// Parameters:
+//   mux - (in/out) object whose chunks are to be assembled
+//   assembled_data - (out) assembled WebP data
+// Returns:
+//   WEBP_MUX_BAD_DATA - if mux object is invalid.
+//   WEBP_MUX_INVALID_ARGUMENT - if mux or assembled_data is NULL.
+//   WEBP_MUX_MEMORY_ERROR - on memory allocation error.
+//   WEBP_MUX_OK - on success.
+WEBP_EXTERN(WebPMuxError) WebPMuxAssemble(WebPMux* mux,
+                                          WebPData* assembled_data);
+
+//------------------------------------------------------------------------------
+// WebPAnimEncoder API
+//
+// This API allows encoding (possibly) animated WebP images.
+//
+// Code Example:
+/*
+  WebPAnimEncoderOptions enc_options;
+  WebPAnimEncoderOptionsInit(&enc_options);
+  // Tune 'enc_options' as needed.
+  WebPAnimEncoder* enc = WebPAnimEncoderNew(width, height, &enc_options);
+  while(<there are more frames>) {
+    WebPConfig config;
+    WebPConfigInit(&config);
+    // Tune 'config' as needed.
+    WebPAnimEncoderAdd(enc, frame, timestamp_ms, &config);
+  }
+  WebPAnimEncoderAdd(enc, NULL, timestamp_ms, NULL);
+  WebPAnimEncoderAssemble(enc, webp_data);
+  WebPAnimEncoderDelete(enc);
+  // Write the 'webp_data' to a file, or re-mux it further.
+*/
+
+typedef struct WebPAnimEncoder WebPAnimEncoder;  // Main opaque object.
+
+// Forward declarations. Defined in encode.h.
+struct WebPPicture;
+struct WebPConfig;
+
+// Global options.
+struct WebPAnimEncoderOptions {
+  WebPMuxAnimParams anim_params;  // Animation parameters.
+  int minimize_size;    // If true, minimize the output size (slow). Implicitly
+                        // disables key-frame insertion.
+  int kmin;
+  int kmax;             // Minimum and maximum distance between consecutive key
+                        // frames in the output. The library may insert some key
+                        // frames as needed to satisfy this criteria.
+                        // Note that these conditions should hold: kmax > kmin
+                        // and kmin >= kmax / 2 + 1. Also, if kmin == 0, then
+                        // key-frame insertion is disabled; and if kmax == 0,
+                        // then all frames will be key-frames.
+  int allow_mixed;      // If true, use mixed compression mode; may choose
+                        // either lossy and lossless for each frame.
+  int verbose;          // If true, print info and warning messages to stderr.
+
+  uint32_t padding[4];  // Padding for later use.
+};
+
+// Internal, version-checked, entry point.
+WEBP_EXTERN(int) WebPAnimEncoderOptionsInitInternal(
+    WebPAnimEncoderOptions*, int);
+
+// Should always be called, to initialize a fresh WebPAnimEncoderOptions
+// structure before modification. Returns false in case of version mismatch.
+// WebPAnimEncoderOptionsInit() must have succeeded before using the
+// 'enc_options' object.
+static WEBP_INLINE int WebPAnimEncoderOptionsInit(
+    WebPAnimEncoderOptions* enc_options) {
+  return WebPAnimEncoderOptionsInitInternal(enc_options, WEBP_MUX_ABI_VERSION);
+}
+
+// Internal, version-checked, entry point.
+WEBP_EXTERN(WebPAnimEncoder*) WebPAnimEncoderNewInternal(
+    int, int, const WebPAnimEncoderOptions*, int);
+
+// Creates and initializes a WebPAnimEncoder object.
+// Parameters:
+//   width/height - (in) canvas width and height of the animation.
+//   enc_options - (in) encoding options; can be passed NULL to pick
+//                      reasonable defaults.
+// Returns:
+//   A pointer to the newly created WebPAnimEncoder object.
+//   Or NULL in case of memory error.
+static WEBP_INLINE WebPAnimEncoder* WebPAnimEncoderNew(
+    int width, int height, const WebPAnimEncoderOptions* enc_options) {
+  return WebPAnimEncoderNewInternal(width, height, enc_options,
+                                    WEBP_MUX_ABI_VERSION);
+}
+
+// Optimize the given frame for WebP, encode it and add it to the
+// WebPAnimEncoder object.
+// The last call to 'WebPAnimEncoderAdd' should be with frame = NULL, which
+// indicates that no more frames are to be added. This call is also used to
+// determine the duration of the last frame.
+// Parameters:
+//   enc - (in/out) object to which the frame is to be added.
+//   frame - (in/out) frame data in ARGB or YUV(A) format. If it is in YUV(A)
+//           format, it will be converted to ARGB, which incurs a small loss.
+//   timestamp_ms - (in) timestamp of this frame in milliseconds.
+//                       Duration of a frame would be calculated as
+//                       "timestamp of next frame - timestamp of this frame".
+//                       Hence, timestamps should be in non-decreasing order.
+//   config - (in) encoding options; can be passed NULL to pick
+//            reasonable defaults.
+// Returns:
+//   On error, returns false and frame->error_code is set appropriately.
+//   Otherwise, returns true.
+WEBP_EXTERN(int) WebPAnimEncoderAdd(
+    WebPAnimEncoder* enc, struct WebPPicture* frame, int timestamp_ms,
+    const struct WebPConfig* config);
+
+// Assemble all frames added so far into a WebP bitstream.
+// This call should be preceded by  a call to 'WebPAnimEncoderAdd' with
+// frame = NULL; if not, the duration of the last frame will be internally
+// estimated.
+// Parameters:
+//   enc - (in/out) object from which the frames are to be assembled.
+//   webp_data - (out) generated WebP bitstream.
+// Returns:
+//   True on success.
+WEBP_EXTERN(int) WebPAnimEncoderAssemble(WebPAnimEncoder* enc,
+                                         WebPData* webp_data);
+
+// Get error string corresponding to the most recent call using 'enc'. The
+// returned string is owned by 'enc' and is valid only until the next call to
+// WebPAnimEncoderAdd() or WebPAnimEncoderAssemble() or WebPAnimEncoderDelete().
+// Parameters:
+//   enc - (in/out) object from which the error string is to be fetched.
+// Returns:
+//   NULL if 'enc' is NULL. Otherwise, returns the error string if the last call
+//   to 'enc' had an error, or an empty string if the last call was a success.
+WEBP_EXTERN(const char*) WebPAnimEncoderGetError(WebPAnimEncoder* enc);
+
+// Deletes the WebPAnimEncoder object.
+// Parameters:
+//   enc - (in/out) object to be deleted
+WEBP_EXTERN(void) WebPAnimEncoderDelete(WebPAnimEncoder* enc);
+
+//------------------------------------------------------------------------------
+
+#ifdef __cplusplus
+}    // extern "C"
+#endif
+
+#endif  /* WEBP_WEBP_MUX_H_ */

+ 97 - 0
Vendor/WebP.framework/Headers/mux_types.h

@@ -0,0 +1,97 @@
+// Copyright 2012 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Data-types common to the mux and demux libraries.
+//
+// Author: Urvang (urvang@google.com)
+
+#ifndef WEBP_WEBP_MUX_TYPES_H_
+#define WEBP_WEBP_MUX_TYPES_H_
+
+#include <stdlib.h>  // free()
+#include <string.h>  // memset()
+#include "./types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Note: forward declaring enumerations is not allowed in (strict) C and C++,
+// the types are left here for reference.
+// typedef enum WebPFeatureFlags WebPFeatureFlags;
+// typedef enum WebPMuxAnimDispose WebPMuxAnimDispose;
+// typedef enum WebPMuxAnimBlend WebPMuxAnimBlend;
+typedef struct WebPData WebPData;
+
+// VP8X Feature Flags.
+typedef enum WebPFeatureFlags {
+  FRAGMENTS_FLAG  = 0x00000001,
+  ANIMATION_FLAG  = 0x00000002,
+  XMP_FLAG        = 0x00000004,
+  EXIF_FLAG       = 0x00000008,
+  ALPHA_FLAG      = 0x00000010,
+  ICCP_FLAG       = 0x00000020
+} WebPFeatureFlags;
+
+// Dispose method (animation only). Indicates how the area used by the current
+// frame is to be treated before rendering the next frame on the canvas.
+typedef enum WebPMuxAnimDispose {
+  WEBP_MUX_DISPOSE_NONE,       // Do not dispose.
+  WEBP_MUX_DISPOSE_BACKGROUND  // Dispose to background color.
+} WebPMuxAnimDispose;
+
+// Blend operation (animation only). Indicates how transparent pixels of the
+// current frame are blended with those of the previous canvas.
+typedef enum WebPMuxAnimBlend {
+  WEBP_MUX_BLEND,              // Blend.
+  WEBP_MUX_NO_BLEND            // Do not blend.
+} WebPMuxAnimBlend;
+
+// Data type used to describe 'raw' data, e.g., chunk data
+// (ICC profile, metadata) and WebP compressed image data.
+struct WebPData {
+  const uint8_t* bytes;
+  size_t size;
+};
+
+// Initializes the contents of the 'webp_data' object with default values.
+static WEBP_INLINE void WebPDataInit(WebPData* webp_data) {
+  if (webp_data != NULL) {
+    memset(webp_data, 0, sizeof(*webp_data));
+  }
+}
+
+// Clears the contents of the 'webp_data' object by calling free(). Does not
+// deallocate the object itself.
+static WEBP_INLINE void WebPDataClear(WebPData* webp_data) {
+  if (webp_data != NULL) {
+    free((void*)webp_data->bytes);
+    WebPDataInit(webp_data);
+  }
+}
+
+// Allocates necessary storage for 'dst' and copies the contents of 'src'.
+// Returns true on success.
+static WEBP_INLINE int WebPDataCopy(const WebPData* src, WebPData* dst) {
+  if (src == NULL || dst == NULL) return 0;
+  WebPDataInit(dst);
+  if (src->bytes != NULL && src->size != 0) {
+    dst->bytes = (uint8_t*)malloc(src->size);
+    if (dst->bytes == NULL) return 0;
+    memcpy((void*)dst->bytes, src->bytes, src->size);
+    dst->size = src->size;
+  }
+  return 1;
+}
+
+#ifdef __cplusplus
+}    // extern "C"
+#endif
+
+#endif  /* WEBP_WEBP_MUX_TYPES_H_ */

+ 52 - 0
Vendor/WebP.framework/Headers/types.h

@@ -0,0 +1,52 @@
+// Copyright 2010 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+//  Common types
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#ifndef WEBP_WEBP_TYPES_H_
+#define WEBP_WEBP_TYPES_H_
+
+#include <stddef.h>  // for size_t
+
+#ifndef _MSC_VER
+#include <inttypes.h>
+#if defined(__cplusplus) || !defined(__STRICT_ANSI__) || \
+    (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L)
+#define WEBP_INLINE inline
+#else
+#define WEBP_INLINE
+#endif
+#else
+typedef signed   char int8_t;
+typedef unsigned char uint8_t;
+typedef signed   short int16_t;
+typedef unsigned short uint16_t;
+typedef signed   int int32_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long int uint64_t;
+typedef long long int int64_t;
+#define WEBP_INLINE __forceinline
+#endif  /* _MSC_VER */
+
+#ifndef WEBP_EXTERN
+// This explicitly marks library functions and allows for changing the
+// signature for e.g., Windows DLL builds.
+# if defined(__GNUC__) && __GNUC__ >= 4
+#  define WEBP_EXTERN(type) extern __attribute__ ((visibility ("default"))) type
+# else
+#  define WEBP_EXTERN(type) extern type
+# endif  /* __GNUC__ >= 4 */
+#endif  /* WEBP_EXTERN */
+
+// Macro to check ABI compatibility (same major revision number)
+#define WEBP_ABI_IS_INCOMPATIBLE(a, b) (((a) >> 8) != ((b) >> 8))
+
+#endif  /* WEBP_WEBP_TYPES_H_ */

BIN
Vendor/WebP.framework/WebP


+ 196 - 0
YYKit/Base/Foundation/NSArray+YYAdd.h

@@ -0,0 +1,196 @@
+//
+//  NSArray+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provide some some common method for `NSArray`.
+ */
+@interface NSArray (YYAdd)
+
+/**
+ Creates and returns an array from a specified property list data.
+ 
+ @param plist   A property list data whose root object is an array.
+ @return A new array created from the binary plist data, or nil if an error occurs.
+ */
++ (nullable NSArray *)arrayWithPlistData:(NSData *)plist;
+
+/**
+ Creates and returns an array from a specified property list xml string.
+ 
+ @param plist   A property list xml string whose root object is an array.
+ @return A new array created from the plist string, or nil if an error occurs.
+ */
++ (nullable NSArray *)arrayWithPlistString:(NSString *)plist;
+
+/**
+ Serialize the array to a binary property list data.
+ 
+ @return A binary plist data, or nil if an error occurs.
+ */
+- (nullable NSData *)plistData;
+
+/**
+ Serialize the array to a xml property list string.
+ 
+ @return A plist xml string, or nil if an error occurs.
+ */
+- (nullable NSString *)plistString;
+
+/**
+ Returns the object located at a random index.
+ 
+ @return The object in the array with a random index value.
+ If the array is empty, returns nil.
+ */
+- (nullable id)randomObject;
+
+/**
+ Returns the object located at index, or return nil when out of bounds.
+ It's similar to `objectAtIndex:`, but it never throw exception.
+ 
+ @param index The object located at index.
+ */
+- (nullable id)objectOrNilAtIndex:(NSUInteger)index;
+
+/**
+ Convert object to json string. return nil if an error occurs.
+ NSString/NSNumber/NSDictionary/NSArray
+ */
+- (nullable NSString *)jsonStringEncoded;
+
+/**
+ Convert object to json string formatted. return nil if an error occurs.
+ */
+- (nullable NSString *)jsonPrettyStringEncoded;
+
+@end
+
+
+/**
+ Provide some some common method for `NSMutableArray`.
+ */
+@interface NSMutableArray (YYAdd)
+
+/**
+ Creates and returns an array from a specified property list data.
+ 
+ @param plist   A property list data whose root object is an array.
+ @return A new array created from the binary plist data, or nil if an error occurs.
+ */
++ (nullable NSMutableArray *)arrayWithPlistData:(NSData *)plist;
+
+/**
+ Creates and returns an array from a specified property list xml string.
+ 
+ @param plist   A property list xml string whose root object is an array.
+ @return A new array created from the plist string, or nil if an error occurs.
+ */
++ (nullable NSMutableArray *)arrayWithPlistString:(NSString *)plist;
+
+/**
+ Removes the object with the lowest-valued index in the array.
+ If the array is empty, this method has no effect.
+ 
+ @discussion Apple has implemented this method, but did not make it public.
+ Override for safe.
+ */
+- (void)removeFirstObject;
+
+/**
+ Removes the object with the highest-valued index in the array.
+ If the array is empty, this method has no effect.
+ 
+ @discussion Apple's implementation said it raises an NSRangeException if the
+ array is empty, but in fact nothing will happen. Override for safe.
+ */
+- (void)removeLastObject;
+
+/**
+ Removes and returns the object with the lowest-valued index in the array.
+ If the array is empty, it just returns nil.
+ 
+ @return The first object, or nil.
+ */
+- (nullable id)popFirstObject;
+
+/**
+ Removes and returns the object with the highest-valued index in the array.
+ If the array is empty, it just returns nil.
+ 
+ @return The first object, or nil.
+ */
+- (nullable id)popLastObject;
+
+/**
+ Inserts a given object at the end of the array.
+ 
+ @param anObject The object to add to the end of the array's content.
+ This value must not be nil. Raises an NSInvalidArgumentException if anObject is nil.
+ */
+- (void)appendObject:(id)anObject;
+
+/**
+ Inserts a given object at the beginning of the array.
+ 
+ @param anObject The object to add to the end of the array's content.
+ This value must not be nil. Raises an NSInvalidArgumentException if anObject is nil.
+ */
+- (void)prependObject:(id)anObject;
+
+/**
+ Adds the objects contained in another given array to the end of the receiving
+ array's content.
+ 
+ @param objects An array of objects to add to the end of the receiving array's
+ content. If the objects is empty or nil, this method has no effect.
+ */
+- (void)appendObjects:(NSArray *)objects;
+
+/**
+ Adds the objects contained in another given array to the beginnin of the receiving
+ array's content.
+ 
+ @param objects An array of objects to add to the beginning of the receiving array's
+ content. If the objects is empty or nil, this method has no effect.
+ */
+- (void)prependObjects:(NSArray *)objects;
+
+/**
+ Adds the objects contained in another given array at the index of the receiving
+ array's content.
+ 
+ @param objects An array of objects to add to the receiving array's
+ content. If the objects is empty or nil, this method has no effect.
+ 
+ @param index The index in the array at which to insert objects. This value must
+ not be greater than the count of elements in the array. Raises an
+ NSRangeException if index is greater than the number of elements in the array.
+ */
+- (void)insertObjects:(NSArray *)objects atIndex:(NSUInteger)index;
+
+/**
+ Reverse the index of object in this array.
+ Example: Before @[ @1, @2, @3 ], After @[ @3, @2, @1 ].
+ */
+- (void)reverse;
+
+/**
+ Sort the object in this array randomly.
+ */
+- (void)shuffle;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 172 - 0
YYKit/Base/Foundation/NSArray+YYAdd.m

@@ -0,0 +1,172 @@
+//
+//  NSArray+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSArray+YYAdd.h"
+#import "YYKitMacro.h"
+#import "NSData+YYAdd.h"
+
+YYSYNTH_DUMMY_CLASS(NSArray_YYAdd)
+
+
+@implementation NSArray (YYAdd)
+
++ (NSArray *)arrayWithPlistData:(NSData *)plist {
+    if (!plist) return nil;
+    NSArray *array = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListImmutable format:NULL error:NULL];
+    if ([array isKindOfClass:[NSArray class]]) return array;
+    return nil;
+}
+
++ (NSArray *)arrayWithPlistString:(NSString *)plist {
+    if (!plist) return nil;
+    NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
+    return [self arrayWithPlistData:data];
+}
+
+- (NSData *)plistData {
+    return [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListBinaryFormat_v1_0 options:kNilOptions error:NULL];
+}
+
+- (NSString *)plistString {
+    NSData *xmlData = [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListXMLFormat_v1_0 options:kNilOptions error:NULL];
+    if (xmlData) return xmlData.utf8String;
+    return nil;
+}
+
+- (id)randomObject {
+    if (self.count) {
+        return self[arc4random_uniform((u_int32_t)self.count)];
+    }
+    return nil;
+}
+
+- (id)objectOrNilAtIndex:(NSUInteger)index {
+    return index < self.count ? self[index] : nil;
+}
+
+- (NSString *)jsonStringEncoded {
+    if ([NSJSONSerialization isValidJSONObject:self]) {
+        NSError *error = nil;
+        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
+        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
+        if (!error) return json;
+    }
+    return nil;
+}
+
+- (NSString *)jsonPrettyStringEncoded {
+    if ([NSJSONSerialization isValidJSONObject:self]) {
+        NSError *error = nil;
+        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
+        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
+        if (!error) return json;
+    }
+    return nil;
+}
+
+@end
+
+
+
+@implementation NSMutableArray (YYAdd)
+
++ (NSMutableArray *)arrayWithPlistData:(NSData *)plist {
+    if (!plist) return nil;
+    NSMutableArray *array = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListMutableContainersAndLeaves format:NULL error:NULL];
+    if ([array isKindOfClass:[NSMutableArray class]]) return array;
+    return nil;
+}
+
++ (NSMutableArray *)arrayWithPlistString:(NSString *)plist {
+    if (!plist) return nil;
+    NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
+    return [self arrayWithPlistData:data];
+}
+
+- (void)removeFirstObject {
+    if (self.count) {
+        [self removeObjectAtIndex:0];
+    }
+}
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+- (void)removeLastObject {
+    if (self.count) {
+        [self removeObjectAtIndex:self.count - 1];
+    }
+}
+
+#pragma clang diagnostic pop
+
+
+- (id)popFirstObject {
+    id obj = nil;
+    if (self.count) {
+        obj = self.firstObject;
+        [self removeFirstObject];
+    }
+    return obj;
+}
+
+- (id)popLastObject {
+    id obj = nil;
+    if (self.count) {
+        obj = self.lastObject;
+        [self removeLastObject];
+    }
+    return obj;
+}
+
+- (void)appendObject:(id)anObject {
+    [self addObject:anObject];
+}
+
+- (void)prependObject:(id)anObject {
+    [self insertObject:anObject atIndex:0];
+}
+
+- (void)appendObjects:(NSArray *)objects {
+    if (!objects) return;
+    [self addObjectsFromArray:objects];
+}
+
+- (void)prependObjects:(NSArray *)objects {
+    if (!objects) return;
+    NSUInteger i = 0;
+    for (id obj in objects) {
+        [self insertObject:obj atIndex:i++];
+    }
+}
+
+- (void)insertObjects:(NSArray *)objects atIndex:(NSUInteger)index {
+    NSUInteger i = index;
+    for (id obj in objects) {
+        [self insertObject:obj atIndex:i++];
+    }
+}
+
+- (void)reverse {
+    NSUInteger count = self.count;
+    int mid = floor(count / 2.0);
+    for (NSUInteger i = 0; i < mid; i++) {
+        [self exchangeObjectAtIndex:i withObjectAtIndex:(count - (i + 1))];
+    }
+}
+
+- (void)shuffle {
+    for (NSUInteger i = self.count; i > 1; i--) {
+        [self exchangeObjectAtIndex:(i - 1)
+                  withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
+    }
+}
+
+@end

+ 92 - 0
YYKit/Base/Foundation/NSBundle+YYAdd.h

@@ -0,0 +1,92 @@
+//
+//  NSBundle+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/20.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `NSBundle` to get resource by @2x or @3x...
+ 
+ Example: ico.png, ico@2x.png, ico@3x.png. Call scaledResource:@"ico" ofType:@"png"
+ on iPhone6 will return "ico@2x.png"'s path.
+ */
+@interface NSBundle (YYAdd)
+
+/**
+ An array of NSNumber objects, shows the best order for path scale search.
+ e.g. iPhone3GS:@[@1,@2,@3] iPhone5:@[@2,@3,@1]  iPhone6 Plus:@[@3,@2,@1]
+ */
++ (NSArray<NSNumber *> *)preferredScales;
+
+/**
+ Returns the full pathname for the resource file identified by the specified 
+ name and extension and residing in a given bundle directory. It first search
+ the file with current screen's scale (such as @2x), then search from higher
+ scale to lower scale.
+ 
+ @param name       The name of a resource file contained in the directory 
+ specified by bundlePath.
+ 
+ @param ext        If extension is an empty string or nil, the extension is 
+ assumed not to exist and the file is the first file encountered that exactly matches name.
+
+ @param bundlePath The path of a top-level bundle directory. This must be a 
+ valid path. For example, to specify the bundle directory for a Mac app, you 
+ might specify the path /Applications/MyApp.app.
+ 
+ @return The full pathname for the resource file or nil if the file could not be
+ located. This method also returns nil if the bundle specified by the bundlePath 
+ parameter does not exist or is not a readable directory.
+ */
++ (nullable NSString *)pathForScaledResource:(NSString *)name
+                                      ofType:(nullable NSString *)ext
+                                 inDirectory:(NSString *)bundlePath;
+
+/**
+ Returns the full pathname for the resource identified by the specified name and 
+ file extension. It first search the file with current screen's scale (such as @2x),
+ then search from higher scale to lower scale.
+ 
+ @param name       The name of the resource file. If name is an empty string or 
+ nil, returns the first file encountered of the supplied type.
+ 
+ @param ext        If extension is an empty string or nil, the extension is 
+ assumed not to exist and the file is the first file encountered that exactly matches name.
+
+ 
+ @return The full pathname for the resource file or nil if the file could not be located.
+ */
+- (nullable NSString *)pathForScaledResource:(NSString *)name ofType:(nullable NSString *)ext;
+
+/**
+ Returns the full pathname for the resource identified by the specified name and 
+ file extension and located in the specified bundle subdirectory. It first search 
+ the file with current screen's scale (such as @2x), then search from higher 
+ scale to lower scale.
+ 
+ @param name       The name of the resource file.
+ 
+ @param ext        If extension is an empty string or nil, all the files in 
+ subpath and its subdirectories are returned. If an extension is provided the 
+ subdirectories are not searched.
+ 
+ @param subpath    The name of the bundle subdirectory. Can be nil.
+ 
+ @return The full pathname for the resource file or nil if the file could not be located.
+ */
+- (nullable NSString *)pathForScaledResource:(NSString *)name
+                                      ofType:(nullable NSString *)ext
+                                 inDirectory:(nullable NSString *)subpath;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 87 - 0
YYKit/Base/Foundation/NSBundle+YYAdd.m

@@ -0,0 +1,87 @@
+//
+//  NSBundle+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/20.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSBundle+YYAdd.h"
+#import "NSString+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(NSBundle_YYAdd)
+
+@implementation NSBundle (YYAdd)
+
++ (NSArray *)preferredScales {
+    static NSArray *scales;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        CGFloat screenScale = [UIScreen mainScreen].scale;
+        if (screenScale <= 1) {
+            scales = @[@1,@2,@3];
+        } else if (screenScale <= 2) {
+            scales = @[@2,@3,@1];
+        } else {
+            scales = @[@3,@2,@1];
+        }
+    });
+    return scales;
+}
+
++ (NSString *)pathForScaledResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)bundlePath {
+    if (name.length == 0) return nil;
+    if ([name hasSuffix:@"/"]) return [self pathForResource:name ofType:ext inDirectory:bundlePath];
+    
+    NSString *path = nil;
+    NSArray *scales = [self preferredScales];
+    for (int s = 0; s < scales.count; s++) {
+        CGFloat scale = ((NSNumber *)scales[s]).floatValue;
+        NSString *scaledName = ext.length ? [name stringByAppendingNameScale:scale]
+        : [name stringByAppendingPathScale:scale];
+        path = [self pathForResource:scaledName ofType:ext inDirectory:bundlePath];
+        if (path) break;
+    }
+    
+    return path;
+}
+
+- (NSString *)pathForScaledResource:(NSString *)name ofType:(NSString *)ext {
+    if (name.length == 0) return nil;
+    if ([name hasSuffix:@"/"]) return [self pathForResource:name ofType:ext];
+    
+    NSString *path = nil;
+    NSArray *scales = [NSBundle preferredScales];
+    for (int s = 0; s < scales.count; s++) {
+        CGFloat scale = ((NSNumber *)scales[s]).floatValue;
+        NSString *scaledName = ext.length ? [name stringByAppendingNameScale:scale]
+        : [name stringByAppendingPathScale:scale];
+        path = [self pathForResource:scaledName ofType:ext];
+        if (path) break;
+    }
+    
+    return path;
+}
+
+- (NSString *)pathForScaledResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath {
+    if (name.length == 0) return nil;
+    if ([name hasSuffix:@"/"]) return [self pathForResource:name ofType:ext];
+    
+    NSString *path = nil;
+    NSArray *scales = [NSBundle preferredScales];
+    for (int s = 0; s < scales.count; s++) {
+        CGFloat scale = ((NSNumber *)scales[s]).floatValue;
+        NSString *scaledName = ext.length ? [name stringByAppendingNameScale:scale]
+        : [name stringByAppendingPathScale:scale];
+        path = [self pathForResource:scaledName ofType:ext inDirectory:subpath];
+        if (path) break;
+    }
+    
+    return path;
+}
+
+@end

+ 310 - 0
YYKit/Base/Foundation/NSData+YYAdd.h

@@ -0,0 +1,310 @@
+//
+//  NSData+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provide hash, encrypt, encode and some common method for `NSData`.
+ */
+@interface NSData (YYAdd)
+
+#pragma mark - Hash
+///=============================================================================
+/// @name Hash
+///=============================================================================
+
+/**
+ Returns a lowercase NSString for md2 hash.
+ */
+- (NSString *)md2String;
+
+/**
+ Returns an NSData for md2 hash.
+ */
+- (NSData *)md2Data;
+
+/**
+ Returns a lowercase NSString for md4 hash.
+ */
+- (NSString *)md4String;
+
+/**
+ Returns an NSData for md4 hash.
+ */
+- (NSData *)md4Data;
+
+/**
+ Returns a lowercase NSString for md5 hash.
+ */
+- (NSString *)md5String;
+
+/**
+ Returns an NSData for md5 hash.
+ */
+- (NSData *)md5Data;
+
+/**
+ Returns a lowercase NSString for sha1 hash.
+ */
+- (NSString *)sha1String;
+
+/**
+ Returns an NSData for sha1 hash.
+ */
+- (NSData *)sha1Data;
+
+/**
+ Returns a lowercase NSString for sha224 hash.
+ */
+- (NSString *)sha224String;
+
+/**
+ Returns an NSData for sha224 hash.
+ */
+- (NSData *)sha224Data;
+
+/**
+ Returns a lowercase NSString for sha256 hash.
+ */
+- (NSString *)sha256String;
+
+/**
+ Returns an NSData for sha256 hash.
+ */
+- (NSData *)sha256Data;
+
+/**
+ Returns a lowercase NSString for sha384 hash.
+ */
+- (NSString *)sha384String;
+
+/**
+ Returns an NSData for sha384 hash.
+ */
+- (NSData *)sha384Data;
+
+/**
+ Returns a lowercase NSString for sha512 hash.
+ */
+- (NSString *)sha512String;
+
+/**
+ Returns an NSData for sha512 hash.
+ */
+- (NSData *)sha512Data;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm md5 with key.
+ @param key  The hmac key.
+ */
+- (NSString *)hmacMD5StringWithKey:(NSString *)key;
+
+/**
+ Returns an NSData for hmac using algorithm md5 with key.
+ @param key  The hmac key.
+ */
+- (NSData *)hmacMD5DataWithKey:(NSData *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha1 with key.
+ @param key  The hmac key.
+ */
+- (NSString *)hmacSHA1StringWithKey:(NSString *)key;
+
+/**
+ Returns an NSData for hmac using algorithm sha1 with key.
+ @param key  The hmac key.
+ */
+- (NSData *)hmacSHA1DataWithKey:(NSData *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha224 with key.
+ @param key  The hmac key.
+ */
+- (NSString *)hmacSHA224StringWithKey:(NSString *)key;
+
+/**
+ Returns an NSData for hmac using algorithm sha224 with key.
+ @param key  The hmac key.
+ */
+- (NSData *)hmacSHA224DataWithKey:(NSData *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha256 with key.
+ @param key  The hmac key.
+ */
+- (NSString *)hmacSHA256StringWithKey:(NSString *)key;
+
+/**
+ Returns an NSData for hmac using algorithm sha256 with key.
+ @param key  The hmac key.
+ */
+- (NSData *)hmacSHA256DataWithKey:(NSData *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha384 with key.
+ @param key  The hmac key.
+ */
+- (NSString *)hmacSHA384StringWithKey:(NSString *)key;
+
+/**
+ Returns an NSData for hmac using algorithm sha384 with key.
+ @param key  The hmac key.
+ */
+- (NSData *)hmacSHA384DataWithKey:(NSData *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha512 with key.
+ @param key  The hmac key.
+ */
+- (NSString *)hmacSHA512StringWithKey:(NSString *)key;
+
+/**
+ Returns an NSData for hmac using algorithm sha512 with key.
+ @param key  The hmac key.
+ */
+- (NSData *)hmacSHA512DataWithKey:(NSData *)key;
+
+/**
+ Returns a lowercase NSString for crc32 hash.
+ */
+- (NSString *)crc32String;
+
+/**
+ Returns crc32 hash.
+ */
+- (uint32_t)crc32;
+
+
+#pragma mark - Encrypt and Decrypt
+///=============================================================================
+/// @name Encrypt and Decrypt
+///=============================================================================
+
+/**
+ Returns an encrypted NSData using AES.
+ 
+ @param key   A key length of 16, 24 or 32 (128, 192 or 256bits).
+ 
+ @param iv    An initialization vector length of 16(128bits).
+              Pass nil when you don't want to use iv.
+ 
+ @return      An NSData encrypted, or nil if an error occurs.
+ */
+- (nullable NSData *)aes256EncryptWithKey:(NSData *)key iv:(nullable NSData *)iv;
+
+/**
+ Returns an decrypted NSData using AES.
+ 
+ @param key   A key length of 16, 24 or 32 (128, 192 or 256bits).
+ 
+ @param iv    An initialization vector length of 16(128bits).
+              Pass nil when you don't want to use iv.
+ 
+ @return      An NSData decrypted, or nil if an error occurs.
+ */
+- (nullable NSData *)aes256DecryptWithkey:(NSData *)key iv:(nullable NSData *)iv;
+
+
+#pragma mark - Encode and decode
+///=============================================================================
+/// @name Encode and decode
+///=============================================================================
+
+/**
+ Returns string decoded in UTF8.
+ */
+- (nullable NSString *)utf8String;
+
+/**
+ Returns a uppercase NSString in HEX.
+ */
+- (nullable NSString *)hexString;
+
+/**
+ Returns an NSData from hex string.
+ 
+ @param hexString   The hex string which is case insensitive.
+ 
+ @return a new NSData, or nil if an error occurs.
+ */
++ (nullable NSData *)dataWithHexString:(NSString *)hexString;
+
+/**
+ Returns an NSString for base64 encoded.
+ */
+- (nullable NSString *)base64EncodedString;
+
+/**
+ Returns an NSData from base64 encoded string.
+ 
+ @warning This method has been implemented in iOS7.
+ 
+ @param base64EncodedString  The encoded string.
+ */
++ (nullable NSData *)dataWithBase64EncodedString:(NSString *)base64EncodedString;
+
+/**
+ Returns an NSDictionary or NSArray for decoded self.
+ Returns nil if an error occurs.
+ */
+- (nullable id)jsonValueDecoded;
+
+
+#pragma mark - Inflate and deflate
+///=============================================================================
+/// @name Inflate and deflate
+///=============================================================================
+
+/**
+ Decompress data from gzip data.
+ @return Inflated data.
+ */
+- (nullable NSData *)gzipInflate;
+
+/**
+ Comperss data to gzip in default compresssion level.
+ @return Deflated data.
+ */
+- (nullable NSData *)gzipDeflate;
+
+/**
+ Decompress data from zlib-compressed data.
+ @return Inflated data.
+ */
+- (nullable NSData *)zlibInflate;
+
+/**
+ Comperss data to zlib-compressed in default compresssion level.
+ @return Deflated data.
+ */
+- (nullable NSData *)zlibDeflate;
+
+
+#pragma mark - Others
+///=============================================================================
+/// @name Others
+///=============================================================================
+
+/**
+ Create data from the file in main bundle (similar to [UIImage imageNamed:]).
+ 
+ @param name The file name (in main bundle).
+ 
+ @return A new data create from the file.
+ */
++ (nullable NSData *)dataNamed:(NSString *)name;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 642 - 0
YYKit/Base/Foundation/NSData+YYAdd.m

@@ -0,0 +1,642 @@
+//
+//  NSData+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSData+YYAdd.h"
+#import "YYKitMacro.h"
+#include <CommonCrypto/CommonCrypto.h>
+#include <zlib.h>
+
+YYSYNTH_DUMMY_CLASS(NSData_YYAdd)
+
+
+@implementation NSData (YYAdd)
+
+- (NSString *)md2String {
+    unsigned char result[CC_MD2_DIGEST_LENGTH];
+    CC_MD2(self.bytes, (CC_LONG)self.length, result);
+    return [NSString stringWithFormat:
+            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+            result[0], result[1], result[2], result[3],
+            result[4], result[5], result[6], result[7],
+            result[8], result[9], result[10], result[11],
+            result[12], result[13], result[14], result[15]
+            ];
+}
+
+- (NSData *)md2Data {
+    unsigned char result[CC_MD2_DIGEST_LENGTH];
+    CC_MD2(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_MD2_DIGEST_LENGTH];
+}
+
+- (NSString *)md4String {
+    unsigned char result[CC_MD4_DIGEST_LENGTH];
+    CC_MD4(self.bytes, (CC_LONG)self.length, result);
+    return [NSString stringWithFormat:
+            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+            result[0], result[1], result[2], result[3],
+            result[4], result[5], result[6], result[7],
+            result[8], result[9], result[10], result[11],
+            result[12], result[13], result[14], result[15]
+            ];
+}
+
+- (NSData *)md4Data {
+    unsigned char result[CC_MD4_DIGEST_LENGTH];
+    CC_MD4(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_MD4_DIGEST_LENGTH];
+}
+
+- (NSString *)md5String {
+    unsigned char result[CC_MD5_DIGEST_LENGTH];
+    CC_MD5(self.bytes, (CC_LONG)self.length, result);
+    return [NSString stringWithFormat:
+            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+            result[0], result[1], result[2], result[3],
+            result[4], result[5], result[6], result[7],
+            result[8], result[9], result[10], result[11],
+            result[12], result[13], result[14], result[15]
+            ];
+}
+
+- (NSData *)md5Data {
+    unsigned char result[CC_MD5_DIGEST_LENGTH];
+    CC_MD5(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH];
+}
+
+- (NSString *)sha1String {
+    unsigned char result[CC_SHA1_DIGEST_LENGTH];
+    CC_SHA1(self.bytes, (CC_LONG)self.length, result);
+    NSMutableString *hash = [NSMutableString
+                             stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
+    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
+        [hash appendFormat:@"%02x", result[i]];
+    }
+    return hash;
+}
+
+- (NSData *)sha1Data {
+    unsigned char result[CC_SHA1_DIGEST_LENGTH];
+    CC_SHA1(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_SHA1_DIGEST_LENGTH];
+}
+
+- (NSString *)sha224String {
+    unsigned char result[CC_SHA224_DIGEST_LENGTH];
+    CC_SHA224(self.bytes, (CC_LONG)self.length, result);
+    NSMutableString *hash = [NSMutableString
+                             stringWithCapacity:CC_SHA224_DIGEST_LENGTH * 2];
+    for (int i = 0; i < CC_SHA224_DIGEST_LENGTH; i++) {
+        [hash appendFormat:@"%02x", result[i]];
+    }
+    return hash;
+}
+
+- (NSData *)sha224Data {
+    unsigned char result[CC_SHA224_DIGEST_LENGTH];
+    CC_SHA224(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_SHA224_DIGEST_LENGTH];
+}
+
+- (NSString *)sha256String {
+    unsigned char result[CC_SHA256_DIGEST_LENGTH];
+    CC_SHA256(self.bytes, (CC_LONG)self.length, result);
+    NSMutableString *hash = [NSMutableString
+                             stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
+    for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
+        [hash appendFormat:@"%02x", result[i]];
+    }
+    return hash;
+}
+
+- (NSData *)sha256Data {
+    unsigned char result[CC_SHA256_DIGEST_LENGTH];
+    CC_SHA256(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_SHA256_DIGEST_LENGTH];
+}
+
+- (NSString *)sha384String {
+    unsigned char result[CC_SHA384_DIGEST_LENGTH];
+    CC_SHA384(self.bytes, (CC_LONG)self.length, result);
+    NSMutableString *hash = [NSMutableString
+                             stringWithCapacity:CC_SHA384_DIGEST_LENGTH * 2];
+    for (int i = 0; i < CC_SHA384_DIGEST_LENGTH; i++) {
+        [hash appendFormat:@"%02x", result[i]];
+    }
+    return hash;
+}
+
+- (NSData *)sha384Data {
+    unsigned char result[CC_SHA384_DIGEST_LENGTH];
+    CC_SHA384(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_SHA384_DIGEST_LENGTH];
+}
+
+- (NSString *)sha512String {
+    unsigned char result[CC_SHA512_DIGEST_LENGTH];
+    CC_SHA512(self.bytes, (CC_LONG)self.length, result);
+    NSMutableString *hash = [NSMutableString
+                             stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
+    for (int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) {
+        [hash appendFormat:@"%02x", result[i]];
+    }
+    return hash;
+}
+
+- (NSData *)sha512Data {
+    unsigned char result[CC_SHA512_DIGEST_LENGTH];
+    CC_SHA512(self.bytes, (CC_LONG)self.length, result);
+    return [NSData dataWithBytes:result length:CC_SHA512_DIGEST_LENGTH];
+}
+
+- (NSString *)hmacStringUsingAlg:(CCHmacAlgorithm)alg withKey:(NSString *)key {
+    size_t size;
+    switch (alg) {
+        case kCCHmacAlgMD5: size = CC_MD5_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA1: size = CC_SHA1_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA224: size = CC_SHA224_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA256: size = CC_SHA256_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA384: size = CC_SHA384_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA512: size = CC_SHA512_DIGEST_LENGTH; break;
+        default: return nil;
+    }
+    unsigned char result[size];
+    const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
+    CCHmac(alg, cKey, strlen(cKey), self.bytes, self.length, result);
+    NSMutableString *hash = [NSMutableString stringWithCapacity:size * 2];
+    for (int i = 0; i < size; i++) {
+        [hash appendFormat:@"%02x", result[i]];
+    }
+    return hash;
+}
+
+- (NSData *)hmacDataUsingAlg:(CCHmacAlgorithm)alg withKey:(NSData *)key {
+    size_t size;
+    switch (alg) {
+        case kCCHmacAlgMD5: size = CC_MD5_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA1: size = CC_SHA1_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA224: size = CC_SHA224_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA256: size = CC_SHA256_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA384: size = CC_SHA384_DIGEST_LENGTH; break;
+        case kCCHmacAlgSHA512: size = CC_SHA512_DIGEST_LENGTH; break;
+        default: return nil;
+    }
+    unsigned char result[size];
+    CCHmac(alg, [key bytes], key.length, self.bytes, self.length, result);
+    return [NSData dataWithBytes:result length:size];
+}
+
+- (NSString *)hmacMD5StringWithKey:(NSString *)key {
+    return [self hmacStringUsingAlg:kCCHmacAlgMD5 withKey:key];
+}
+
+- (NSData *)hmacMD5DataWithKey:(NSData *)key {
+    return [self hmacDataUsingAlg:kCCHmacAlgMD5 withKey:key];
+}
+
+- (NSString *)hmacSHA1StringWithKey:(NSString *)key {
+    return [self hmacStringUsingAlg:kCCHmacAlgSHA1 withKey:key];
+}
+
+- (NSData *)hmacSHA1DataWithKey:(NSData *)key {
+    return [self hmacDataUsingAlg:kCCHmacAlgSHA1 withKey:key];
+}
+
+- (NSString *)hmacSHA224StringWithKey:(NSString *)key {
+    return [self hmacStringUsingAlg:kCCHmacAlgSHA224 withKey:key];
+}
+
+- (NSData *)hmacSHA224DataWithKey:(NSData *)key {
+    return [self hmacDataUsingAlg:kCCHmacAlgSHA224 withKey:key];
+}
+
+- (NSString *)hmacSHA256StringWithKey:(NSString *)key {
+    return [self hmacStringUsingAlg:kCCHmacAlgSHA256 withKey:key];
+}
+
+- (NSData *)hmacSHA256DataWithKey:(NSData *)key {
+    return [self hmacDataUsingAlg:kCCHmacAlgSHA256 withKey:key];
+}
+
+- (NSString *)hmacSHA384StringWithKey:(NSString *)key {
+    return [self hmacStringUsingAlg:kCCHmacAlgSHA384 withKey:key];
+}
+
+- (NSData *)hmacSHA384DataWithKey:(NSData *)key {
+    return [self hmacDataUsingAlg:kCCHmacAlgSHA384 withKey:key];
+}
+
+- (NSString *)hmacSHA512StringWithKey:(NSString *)key {
+    return [self hmacStringUsingAlg:kCCHmacAlgSHA512 withKey:key];
+}
+
+- (NSData *)hmacSHA512DataWithKey:(NSData *)key {
+    return [self hmacDataUsingAlg:kCCHmacAlgSHA512 withKey:key];
+}
+
+- (NSString *)crc32String {
+    uLong result = crc32(0, self.bytes, (uInt)self.length);
+    return [NSString stringWithFormat:@"%08x", (uint32_t)result];
+}
+
+- (uint32_t)crc32 {
+    uLong result = crc32(0, self.bytes, (uInt)self.length);
+    return (uint32_t)result;
+}
+
+- (NSData *)aes256EncryptWithKey:(NSData *)key iv:(NSData *)iv {
+    if (key.length != 16 && key.length != 24 && key.length != 32) {
+        return nil;
+    }
+    if (iv.length != 16 && iv.length != 0) {
+        return nil;
+    }
+    
+    NSData *result = nil;
+    size_t bufferSize = self.length + kCCBlockSizeAES128;
+    void *buffer = malloc(bufferSize);
+    if (!buffer) return nil;
+    size_t encryptedSize = 0;
+    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
+                                          kCCAlgorithmAES128,
+                                          kCCOptionPKCS7Padding,
+                                          key.bytes,
+                                          key.length,
+                                          iv.bytes,
+                                          self.bytes,
+                                          self.length,
+                                          buffer,
+                                          bufferSize,
+                                          &encryptedSize);
+    if (cryptStatus == kCCSuccess) {
+        result = [[NSData alloc]initWithBytes:buffer length:encryptedSize];
+        free(buffer);
+        return result;
+    } else {
+        free(buffer);
+        return nil;
+    }
+}
+
+- (NSData *)aes256DecryptWithkey:(NSData *)key iv:(NSData *)iv {
+    if (key.length != 16 && key.length != 24 && key.length != 32) {
+        return nil;
+    }
+    if (iv.length != 16 && iv.length != 0) {
+        return nil;
+    }
+    
+    NSData *result = nil;
+    size_t bufferSize = self.length + kCCBlockSizeAES128;
+    void *buffer = malloc(bufferSize);
+    if (!buffer) return nil;
+    size_t encryptedSize = 0;
+    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
+                                          kCCAlgorithmAES128,
+                                          kCCOptionPKCS7Padding,
+                                          key.bytes,
+                                          key.length,
+                                          iv.bytes,
+                                          self.bytes,
+                                          self.length,
+                                          buffer,
+                                          bufferSize,
+                                          &encryptedSize);
+    if (cryptStatus == kCCSuccess) {
+        result = [[NSData alloc]initWithBytes:buffer length:encryptedSize];
+        free(buffer);
+        return result;
+    } else {
+        free(buffer);
+        return nil;
+    }
+}
+
+- (NSString *)utf8String {
+    if (self.length > 0) {
+        return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
+    }
+    return @"";
+}
+
+- (NSString *)hexString {
+    NSUInteger length = self.length;
+    NSMutableString *result = [NSMutableString stringWithCapacity:length * 2];
+    const unsigned char *byte = self.bytes;
+    for (int i = 0; i < length; i++, byte++) {
+        [result appendFormat:@"%02X", *byte];
+    }
+    return result;
+}
+
++ (NSData *)dataWithHexString:(NSString *)hexStr {
+    hexStr = [hexStr stringByReplacingOccurrencesOfString:@" " withString:@""];
+    hexStr = [hexStr lowercaseString];
+    NSUInteger len = hexStr.length;
+    if (!len) return nil;
+    unichar *buf = malloc(sizeof(unichar) * len);
+    if (!buf) return nil;
+    [hexStr getCharacters:buf range:NSMakeRange(0, len)];
+    
+    NSMutableData *result = [NSMutableData data];
+    unsigned char bytes;
+    char str[3] = { '\0', '\0', '\0' };
+    int i;
+    for (i = 0; i < len / 2; i++) {
+        str[0] = buf[i * 2];
+        str[1] = buf[i * 2 + 1];
+        bytes = strtol(str, NULL, 16);
+        [result appendBytes:&bytes length:1];
+    }
+    free(buf);
+    return result;
+}
+
+static const char base64EncodingTable[64]
+= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static const short base64DecodingTable[256] = {
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2,  -1,  -1, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62,  -2,  -2, -2, 63,
+    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2,  -2,  -2, -2, -2,
+    -2, 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10,  11,  12, 13, 14,
+    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2,  -2,  -2, -2, -2,
+    -2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,  37,  38, 39, 40,
+    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2,
+    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  -2,  -2, -2, -2
+};
+
+- (NSString *)base64EncodedString {
+    NSUInteger length = self.length;
+    if (length == 0)
+        return @"";
+    
+    NSUInteger out_length = ((length + 2) / 3) * 4;
+    uint8_t *output = malloc(((out_length + 2) / 3) * 4);
+    if (output == NULL)
+        return nil;
+    
+    const char *input = self.bytes;
+    NSInteger i, value;
+    for (i = 0; i < length; i += 3) {
+        value = 0;
+        for (NSInteger j = i; j < i + 3; j++) {
+            value <<= 8;
+            if (j < length) {
+                value |= (0xFF & input[j]);
+            }
+        }
+        NSInteger index = (i / 3) * 4;
+        output[index + 0] = base64EncodingTable[(value >> 18) & 0x3F];
+        output[index + 1] = base64EncodingTable[(value >> 12) & 0x3F];
+        output[index + 2] = ((i + 1) < length)
+        ? base64EncodingTable[(value >> 6) & 0x3F]
+        : '=';
+        output[index + 3] = ((i + 2) < length)
+        ? base64EncodingTable[(value >> 0) & 0x3F]
+        : '=';
+    }
+    
+    NSString *base64 = [[NSString alloc] initWithBytes:output
+                                                length:out_length
+                                              encoding:NSASCIIStringEncoding];
+    free(output);
+    return base64;
+}
+
++ (NSData *)dataWithBase64EncodedString:(NSString *)base64EncodedString {
+    NSInteger length = base64EncodedString.length;
+    const char *string = [base64EncodedString cStringUsingEncoding:NSASCIIStringEncoding];
+    if (string  == NULL)
+        return nil;
+    
+    while (length > 0 && string[length - 1] == '=')
+        length--;
+    
+    NSInteger outputLength = length * 3 / 4;
+    NSMutableData *data = [NSMutableData dataWithLength:outputLength];
+    if (data == nil)
+        return nil;
+    if (length == 0)
+        return data;
+    
+    uint8_t *output = data.mutableBytes;
+    NSInteger inputPoint = 0;
+    NSInteger outputPoint = 0;
+    while (inputPoint < length) {
+        char i0 = string[inputPoint++];
+        char i1 = string[inputPoint++];
+        char i2 = inputPoint < length ? string[inputPoint++] : 'A';
+        char i3 = inputPoint < length ? string[inputPoint++] : 'A';
+        
+        output[outputPoint++] = (base64DecodingTable[i0] << 2)
+        | (base64DecodingTable[i1] >> 4);
+        if (outputPoint < outputLength) {
+            output[outputPoint++] = ((base64DecodingTable[i1] & 0xf) << 4)
+            | (base64DecodingTable[i2] >> 2);
+        }
+        if (outputPoint < outputLength) {
+            output[outputPoint++] = ((base64DecodingTable[i2] & 0x3) << 6)
+            | base64DecodingTable[i3];
+        }
+    }
+    
+    return data;
+}
+
+- (id)jsonValueDecoded {
+    NSError *error = nil;
+    id value = [NSJSONSerialization JSONObjectWithData:self options:kNilOptions error:&error];
+    if (error) {
+        NSLog(@"jsonValueDecoded error:%@", error);
+    }
+    return value;
+}
+
+- (NSData *)gzipInflate {
+    if ([self length] == 0) return self;
+    
+    unsigned full_length = (unsigned)[self length];
+    unsigned half_length = (unsigned)[self length] / 2;
+    
+    NSMutableData *decompressed = [NSMutableData
+                                   dataWithLength:full_length + half_length];
+    BOOL done = NO;
+    int status;
+    
+    z_stream strm;
+    strm.next_in = (Bytef *)[self bytes];
+    strm.avail_in = (unsigned)[self length];
+    strm.total_out = 0;
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    
+    if (inflateInit2(&strm, (15 + 32)) != Z_OK) return nil;
+    while (!done) {
+        // Make sure we have enough room and reset the lengths.
+        if (strm.total_out >= [decompressed length])
+            [decompressed increaseLengthBy:half_length];
+        strm.next_out = [decompressed mutableBytes] + strm.total_out;
+        strm.avail_out = (uInt)([decompressed length] - strm.total_out);
+        
+        // Inflate another chunk.
+        status = inflate(&strm, Z_SYNC_FLUSH);
+        if (status == Z_STREAM_END) done = YES;
+        else if (status != Z_OK) break;
+    }
+    if (inflateEnd(&strm) != Z_OK) return nil;
+    
+    // Set real length.
+    if (done) {
+        [decompressed setLength:strm.total_out];
+        return [NSData dataWithData:decompressed];
+    } else return nil;
+}
+
+- (NSData *)gzipDeflate {
+    if ([self length] == 0) return self;
+    
+    z_stream strm;
+    
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.total_out = 0;
+    strm.next_in = (Bytef *)[self bytes];
+    strm.avail_in = (uInt)[self length];
+    
+    // Compresssion Levels:
+    //   Z_NO_COMPRESSION
+    //   Z_BEST_SPEED
+    //   Z_BEST_COMPRESSION
+    //   Z_DEFAULT_COMPRESSION
+    
+    if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15 + 16),
+                     8, Z_DEFAULT_STRATEGY) != Z_OK)
+        return nil;
+    
+    // 16K chunks for expansion
+    NSMutableData *compressed = [NSMutableData dataWithLength:16384];
+    
+    do {
+        if (strm.total_out >= [compressed length])
+            [compressed increaseLengthBy:16384];
+        
+        strm.next_out = [compressed mutableBytes] + strm.total_out;
+        strm.avail_out = (uInt)([compressed length] - strm.total_out);
+        
+        deflate(&strm, Z_FINISH);
+    }
+    while (strm.avail_out == 0);
+    
+    deflateEnd(&strm);
+    
+    [compressed setLength:strm.total_out];
+    return [NSData dataWithData:compressed];
+}
+
+- (NSData *)zlibInflate {
+    if ([self length] == 0) return self;
+    
+    NSUInteger full_length = [self length];
+    NSUInteger half_length = [self length] / 2;
+    
+    NSMutableData *decompressed = [NSMutableData
+                                   dataWithLength:full_length + half_length];
+    BOOL done = NO;
+    int status;
+    
+    z_stream strm;
+    strm.next_in = (Bytef *)[self bytes];
+    strm.avail_in = (uInt)full_length;
+    strm.total_out = 0;
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    
+    if (inflateInit(&strm) != Z_OK) return nil;
+    
+    while (!done) {
+        // Make sure we have enough room and reset the lengths.
+        if (strm.total_out >= [decompressed length])
+            [decompressed increaseLengthBy:half_length];
+        strm.next_out = [decompressed mutableBytes] + strm.total_out;
+        strm.avail_out = (uInt)([decompressed length] - strm.total_out);
+        
+        // Inflate another chunk.
+        status = inflate(&strm, Z_SYNC_FLUSH);
+        if (status == Z_STREAM_END) done = YES;
+        else if (status != Z_OK) break;
+    }
+    if (inflateEnd(&strm) != Z_OK) return nil;
+    
+    // Set real length.
+    if (done) {
+        [decompressed setLength:strm.total_out];
+        return [NSData dataWithData:decompressed];
+    } else return nil;
+}
+
+- (NSData *)zlibDeflate {
+    if ([self length] == 0) return self;
+    
+    z_stream strm;
+    
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.total_out = 0;
+    strm.next_in = (Bytef *)[self bytes];
+    strm.avail_in = (uInt)[self length];
+    
+    // Compresssion Levels:
+    //   Z_NO_COMPRESSION
+    //   Z_BEST_SPEED
+    //   Z_BEST_COMPRESSION
+    //   Z_DEFAULT_COMPRESSION
+    
+    if (deflateInit(&strm, Z_DEFAULT_COMPRESSION) != Z_OK) return nil;
+    
+    // 16K chuncks for expansion
+    NSMutableData *compressed = [NSMutableData dataWithLength:16384];
+    
+    do {
+        if (strm.total_out >= [compressed length])
+            [compressed increaseLengthBy:16384];
+        
+        strm.next_out = [compressed mutableBytes] + strm.total_out;
+        strm.avail_out = (uInt)([compressed length] - strm.total_out);
+        
+        deflate(&strm, Z_FINISH);
+    }
+    while (strm.avail_out == 0);
+    
+    deflateEnd(&strm);
+    
+    [compressed setLength:strm.total_out];
+    return [NSData dataWithData:compressed];
+}
+
++ (NSData *)dataNamed:(NSString *)name {
+    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@""];
+    if (!path) return nil;
+    NSData *data = [NSData dataWithContentsOfFile:path];
+    return data;
+}
+
+@end

+ 188 - 0
YYKit/Base/Foundation/NSDate+YYAdd.h

@@ -0,0 +1,188 @@
+//
+//  NSDate+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `NSDate`.
+ */
+@interface NSDate (YYAdd)
+
+#pragma mark - Component Properties
+///=============================================================================
+/// @name Component Properties
+///=============================================================================
+
+@property (nonatomic, readonly) NSInteger year; ///< Year component
+@property (nonatomic, readonly) NSInteger month; ///< Month component (1~12)
+@property (nonatomic, readonly) NSInteger day; ///< Day component (1~31)
+@property (nonatomic, readonly) NSInteger hour; ///< Hour component (0~23)
+@property (nonatomic, readonly) NSInteger minute; ///< Minute component (0~59)
+@property (nonatomic, readonly) NSInteger second; ///< Second component (0~59)
+@property (nonatomic, readonly) NSInteger nanosecond; ///< Nanosecond component
+@property (nonatomic, readonly) NSInteger weekday; ///< Weekday component (1~7, first day is based on user setting)
+@property (nonatomic, readonly) NSInteger weekdayOrdinal; ///< WeekdayOrdinal component
+@property (nonatomic, readonly) NSInteger weekOfMonth; ///< WeekOfMonth component (1~5)
+@property (nonatomic, readonly) NSInteger weekOfYear; ///< WeekOfYear component (1~53)
+@property (nonatomic, readonly) NSInteger yearForWeekOfYear; ///< YearForWeekOfYear component
+@property (nonatomic, readonly) NSInteger quarter; ///< Quarter component
+@property (nonatomic, readonly) BOOL isLeapMonth; ///< whether the month is leap month
+@property (nonatomic, readonly) BOOL isLeapYear; ///< whether the year is leap year
+@property (nonatomic, readonly) BOOL isToday; ///< whether date is today (based on current locale)
+@property (nonatomic, readonly) BOOL isYesterday; ///< whether date is yesterday (based on current locale)
+
+#pragma mark - Date modify
+///=============================================================================
+/// @name Date modify
+///=============================================================================
+
+/**
+ Returns a date representing the receiver date shifted later by the provided number of years.
+ 
+ @param years  Number of years to add.
+ @return Date modified by the number of desired years.
+ */
+- (nullable NSDate *)dateByAddingYears:(NSInteger)years;
+
+/**
+ Returns a date representing the receiver date shifted later by the provided number of months.
+ 
+ @param months  Number of months to add.
+ @return Date modified by the number of desired months.
+ */
+- (nullable NSDate *)dateByAddingMonths:(NSInteger)months;
+
+/**
+ Returns a date representing the receiver date shifted later by the provided number of weeks.
+ 
+ @param weeks  Number of weeks to add.
+ @return Date modified by the number of desired weeks.
+ */
+- (nullable NSDate *)dateByAddingWeeks:(NSInteger)weeks;
+
+/**
+ Returns a date representing the receiver date shifted later by the provided number of days.
+ 
+ @param days  Number of days to add.
+ @return Date modified by the number of desired days.
+ */
+- (nullable NSDate *)dateByAddingDays:(NSInteger)days;
+
+/**
+ Returns a date representing the receiver date shifted later by the provided number of hours.
+ 
+ @param hours  Number of hours to add.
+ @return Date modified by the number of desired hours.
+ */
+- (nullable NSDate *)dateByAddingHours:(NSInteger)hours;
+
+/**
+ Returns a date representing the receiver date shifted later by the provided number of minutes.
+ 
+ @param minutes  Number of minutes to add.
+ @return Date modified by the number of desired minutes.
+ */
+- (nullable NSDate *)dateByAddingMinutes:(NSInteger)minutes;
+
+/**
+ Returns a date representing the receiver date shifted later by the provided number of seconds.
+ 
+ @param seconds  Number of seconds to add.
+ @return Date modified by the number of desired seconds.
+ */
+- (nullable NSDate *)dateByAddingSeconds:(NSInteger)seconds;
+
+
+#pragma mark - Date Format
+///=============================================================================
+/// @name Date Format
+///=============================================================================
+
+/**
+ Returns a formatted string representing this date.
+ see http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
+ for format description.
+ 
+ @param format   String representing the desired date format.
+ e.g. @"yyyy-MM-dd HH:mm:ss"
+ 
+ @return NSString representing the formatted date string.
+ */
+- (nullable NSString *)stringWithFormat:(NSString *)format;
+
+/**
+ Returns a formatted string representing this date.
+ see http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
+ for format description.
+ 
+ @param format    String representing the desired date format.
+ e.g. @"yyyy-MM-dd HH:mm:ss"
+ 
+ @param timeZone  Desired time zone.
+ 
+ @param locale    Desired locale.
+ 
+ @return NSString representing the formatted date string.
+ */
+- (nullable NSString *)stringWithFormat:(NSString *)format
+                               timeZone:(nullable NSTimeZone *)timeZone
+                                 locale:(nullable NSLocale *)locale;
+
+/**
+ Returns a string representing this date in ISO8601 format.
+ e.g. "2010-07-09T16:13:30+12:00"
+ 
+ @return NSString representing the formatted date string in ISO8601.
+ */
+- (nullable NSString *)stringWithISOFormat;
+
+/**
+ Returns a date parsed from given string interpreted using the format.
+ 
+ @param dateString The string to parse.
+ @param format     The string's date format.
+ 
+ @return A date representation of string interpreted using the format.
+ If can not parse the string, returns nil.
+ */
++ (nullable NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format;
+
+/**
+ Returns a date parsed from given string interpreted using the format.
+ 
+ @param dateString The string to parse.
+ @param format     The string's date format.
+ @param timeZone   The time zone, can be nil.
+ @param locale     The locale, can be nil.
+ 
+ @return A date representation of string interpreted using the format.
+ If can not parse the string, returns nil.
+ */
++ (nullable NSDate *)dateWithString:(NSString *)dateString
+                             format:(NSString *)format
+                           timeZone:(nullable NSTimeZone *)timeZone
+                             locale:(nullable NSLocale *)locale;
+
+/**
+ Returns a date parsed from given string interpreted using the ISO8601 format.
+ 
+ @param dateString The date string in ISO8601 format. e.g. "2010-07-09T16:13:30+12:00"
+ 
+ @return A date representation of string interpreted using the format.
+ If can not parse the string, returns nil.
+ */
++ (nullable NSDate *)dateWithISOFormatString:(NSString *)dateString;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 188 - 0
YYKit/Base/Foundation/NSDate+YYAdd.m

@@ -0,0 +1,188 @@
+//
+//  NSDate+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSDate+YYAdd.h"
+#import "YYKitMacro.h"
+#import <time.h>
+
+YYSYNTH_DUMMY_CLASS(NSDate_YYAdd)
+
+
+@implementation NSDate (YYAdd)
+
+- (NSInteger)year {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:self] year];
+}
+
+- (NSInteger)month {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitMonth fromDate:self] month];
+}
+
+- (NSInteger)day {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:self] day];
+}
+
+- (NSInteger)hour {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:self] hour];
+}
+
+- (NSInteger)minute {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitMinute fromDate:self] minute];
+}
+
+- (NSInteger)second {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitSecond fromDate:self] second];
+}
+
+- (NSInteger)nanosecond {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitSecond fromDate:self] nanosecond];
+}
+
+- (NSInteger)weekday {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:self] weekday];
+}
+
+- (NSInteger)weekdayOrdinal {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekdayOrdinal fromDate:self] weekdayOrdinal];
+}
+
+- (NSInteger)weekOfMonth {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekOfMonth fromDate:self] weekOfMonth];
+}
+
+- (NSInteger)weekOfYear {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekOfYear fromDate:self] weekOfYear];
+}
+
+- (NSInteger)yearForWeekOfYear {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitYearForWeekOfYear fromDate:self] yearForWeekOfYear];
+}
+
+- (NSInteger)quarter {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitQuarter fromDate:self] quarter];
+}
+
+- (BOOL)isLeapMonth {
+    return [[[NSCalendar currentCalendar] components:NSCalendarUnitQuarter fromDate:self] isLeapMonth];
+}
+
+- (BOOL)isLeapYear {
+    NSUInteger year = self.year;
+    return ((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0)));
+}
+
+- (BOOL)isToday {
+    if (fabs(self.timeIntervalSinceNow) >= 60 * 60 * 24) return NO;
+    return [NSDate new].day == self.day;
+}
+
+- (BOOL)isYesterday {
+    NSDate *added = [self dateByAddingDays:1];
+    return [added isToday];
+}
+
+- (NSDate *)dateByAddingYears:(NSInteger)years {
+    NSCalendar *calendar =  [NSCalendar currentCalendar];
+    NSDateComponents *components = [[NSDateComponents alloc] init];
+    [components setYear:years];
+    return [calendar dateByAddingComponents:components toDate:self options:0];
+}
+
+- (NSDate *)dateByAddingMonths:(NSInteger)months {
+    NSCalendar *calendar = [NSCalendar currentCalendar];
+    NSDateComponents *components = [[NSDateComponents alloc] init];
+    [components setMonth:months];
+    return [calendar dateByAddingComponents:components toDate:self options:0];
+}
+
+- (NSDate *)dateByAddingWeeks:(NSInteger)weeks {
+    NSCalendar *calendar = [NSCalendar currentCalendar];
+    NSDateComponents *components = [[NSDateComponents alloc] init];
+    [components setWeekOfYear:weeks];
+    return [calendar dateByAddingComponents:components toDate:self options:0];
+}
+
+- (NSDate *)dateByAddingDays:(NSInteger)days {
+    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 86400 * days;
+    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
+    return newDate;
+}
+
+- (NSDate *)dateByAddingHours:(NSInteger)hours {
+    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 3600 * hours;
+    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
+    return newDate;
+}
+
+- (NSDate *)dateByAddingMinutes:(NSInteger)minutes {
+    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 60 * minutes;
+    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
+    return newDate;
+}
+
+- (NSDate *)dateByAddingSeconds:(NSInteger)seconds {
+    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + seconds;
+    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
+    return newDate;
+}
+
+- (NSString *)stringWithFormat:(NSString *)format {
+    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
+    [formatter setDateFormat:format];
+    [formatter setLocale:[NSLocale currentLocale]];
+    return [formatter stringFromDate:self];
+}
+
+- (NSString *)stringWithFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
+    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
+    [formatter setDateFormat:format];
+    if (timeZone) [formatter setTimeZone:timeZone];
+    if (locale) [formatter setLocale:locale];
+    return [formatter stringFromDate:self];
+}
+
+- (NSString *)stringWithISOFormat {
+    static NSDateFormatter *formatter = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        formatter = [[NSDateFormatter alloc] init];
+        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
+        formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
+    });
+    return [formatter stringFromDate:self];
+}
+
++ (NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format {
+    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
+    [formatter setDateFormat:format];
+    return [formatter dateFromString:dateString];
+}
+
++ (NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
+    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
+    [formatter setDateFormat:format];
+    if (timeZone) [formatter setTimeZone:timeZone];
+    if (locale) [formatter setLocale:locale];
+    return [formatter dateFromString:dateString];
+}
+
++ (NSDate *)dateWithISOFormatString:(NSString *)dateString {
+    static NSDateFormatter *formatter = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        formatter = [[NSDateFormatter alloc] init];
+        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
+        formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
+    });
+    return [formatter dateFromString:dateString];
+}
+
+@end

+ 197 - 0
YYKit/Base/Foundation/NSDictionary+YYAdd.h

@@ -0,0 +1,197 @@
+//
+//  NSDictionary+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provide some some common method for `NSDictionary`.
+ */
+@interface NSDictionary (YYAdd)
+
+#pragma mark - Dictionary Convertor
+///=============================================================================
+/// @name Dictionary Convertor
+///=============================================================================
+
+/**
+ Creates and returns a dictionary from a specified property list data.
+ 
+ @param plist   A property list data whose root object is a dictionary.
+ @return A new dictionary created from the binary plist data, or nil if an error occurs.
+ */
++ (nullable NSDictionary *)dictionaryWithPlistData:(NSData *)plist;
+
+/**
+ Creates and returns a dictionary from a specified property list xml string.
+ 
+ @param plist   A property list xml string whose root object is a dictionary.
+ @return A new dictionary created from the plist string, or nil if an error occurs.
+ 
+ @discussion Apple has implemented this method, but did not make it public.
+ */
++ (nullable NSDictionary *)dictionaryWithPlistString:(NSString *)plist;
+
+/**
+ Serialize the dictionary to a binary property list data.
+ 
+ @return A binary plist data, or nil if an error occurs.
+ 
+ @discussion Apple has implemented this method, but did not make it public.
+ */
+- (nullable NSData *)plistData;
+
+/**
+ Serialize the dictionary to a xml property list string.
+ 
+ @return A plist xml string, or nil if an error occurs.
+ */
+- (nullable NSString *)plistString;
+
+/**
+ Returns a new array containing the dictionary's keys sorted.
+ The keys should be NSString, and they will be sorted ascending.
+ 
+ @return A new array containing the dictionary's keys,
+ or an empty array if the dictionary has no entries.
+ */
+- (NSArray *)allKeysSorted;
+
+/**
+ Returns a new array containing the dictionary's values sorted by keys.
+ 
+ The order of the values in the array is defined by keys.
+ The keys should be NSString, and they will be sorted ascending.
+ 
+ @return A new array containing the dictionary's values sorted by keys,
+ or an empty array if the dictionary has no entries.
+ */
+- (NSArray *)allValuesSortedByKeys;
+
+/**
+ Returns a BOOL value tells if the dictionary has an object for key.
+ 
+ @param key The key.
+ */
+- (BOOL)containsObjectForKey:(id)key;
+
+/**
+ Returns a new dictionary containing the entries for keys.
+ If the keys is empty or nil, it just returns an empty dictionary.
+ 
+ @param keys The keys.
+ @return The entries for the keys.
+ */
+- (NSDictionary *)entriesForKeys:(NSArray *)keys;
+
+/**
+ Convert dictionary to json string. return nil if an error occurs.
+ */
+- (nullable NSString *)jsonStringEncoded;
+
+/**
+ Convert dictionary to json string formatted. return nil if an error occurs.
+ */
+- (nullable NSString *)jsonPrettyStringEncoded;
+
+/**
+ Try to parse an XML and wrap it into a dictionary.
+ If you just want to get some value from a small xml, try this.
+ 
+ example XML: "<config><a href="test.com">link</a></config>"
+ example Return: @{@"_name":@"config", @"a":{@"_text":@"link",@"href":@"test.com"}}
+ 
+ @param xmlDataOrString XML in NSData or NSString format.
+ @return Return a new dictionary, or nil if an error occurs.
+ */
++ (nullable NSDictionary *)dictionaryWithXML:(id)xmlDataOrString;
+
+#pragma mark - Dictionary Value Getter
+///=============================================================================
+/// @name Dictionary Value Getter
+///=============================================================================
+
+- (BOOL)boolValueForKey:(NSString *)key default:(BOOL)def;
+
+- (char)charValueForKey:(NSString *)key default:(char)def;
+- (unsigned char)unsignedCharValueForKey:(NSString *)key default:(unsigned char)def;
+
+- (short)shortValueForKey:(NSString *)key default:(short)def;
+- (unsigned short)unsignedShortValueForKey:(NSString *)key default:(unsigned short)def;
+
+- (int)intValueForKey:(NSString *)key default:(int)def;
+- (unsigned int)unsignedIntValueForKey:(NSString *)key default:(unsigned int)def;
+
+- (long)longValueForKey:(NSString *)key default:(long)def;
+- (unsigned long)unsignedLongValueForKey:(NSString *)key default:(unsigned long)def;
+
+- (long long)longLongValueForKey:(NSString *)key default:(long long)def;
+- (unsigned long long)unsignedLongLongValueForKey:(NSString *)key default:(unsigned long long)def;
+
+- (float)floatValueForKey:(NSString *)key default:(float)def;
+- (double)doubleValueForKey:(NSString *)key default:(double)def;
+
+- (NSInteger)integerValueForKey:(NSString *)key default:(NSInteger)def;
+- (NSUInteger)unsignedIntegerValueForKey:(NSString *)key default:(NSUInteger)def;
+
+- (nullable NSNumber *)numberValueForKey:(NSString *)key default:(nullable NSNumber *)def;
+- (nullable NSString *)stringValueForKey:(NSString *)key default:(nullable NSString *)def;
+
+@end
+
+
+
+/**
+ Provide some some common method for `NSMutableDictionary`.
+ */
+@interface NSMutableDictionary (YYAdd)
+
+/**
+ Creates and returns a dictionary from a specified property list data.
+ 
+ @param plist   A property list data whose root object is a dictionary.
+ @return A new dictionary created from the binary plist data, or nil if an error occurs.
+ 
+ @discussion Apple has implemented this method, but did not make it public.
+ */
++ (nullable NSMutableDictionary *)dictionaryWithPlistData:(NSData *)plist;
+
+/**
+ Creates and returns a dictionary from a specified property list xml string.
+ 
+ @param plist   A property list xml string whose root object is a dictionary.
+ @return A new dictionary created from the plist string, or nil if an error occurs.
+ */
++ (nullable NSMutableDictionary *)dictionaryWithPlistString:(NSString *)plist;
+
+
+/**
+ Removes and returns the value associated with a given key.
+ 
+ @param aKey The key for which to return and remove the corresponding value.
+ @return The value associated with aKey, or nil if no value is associated with aKey.
+ */
+- (nullable id)popObjectForKey:(id)aKey;
+
+/**
+ Returns a new dictionary containing the entries for keys, and remove these
+ entries from receiver. If the keys is empty or nil, it just returns an
+ empty dictionary.
+ 
+ @param keys The keys.
+ @return The entries for the keys.
+ */
+- (NSDictionary *)popEntriesForKeys:(NSArray *)keys;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 392 - 0
YYKit/Base/Foundation/NSDictionary+YYAdd.m

@@ -0,0 +1,392 @@
+//
+//  NSDictionary+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSDictionary+YYAdd.h"
+#import "NSString+YYAdd.h"
+#import "NSData+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(NSDictionary_YYAdd)
+
+
+@interface _YYXMLDictionaryParser : NSObject <NSXMLParserDelegate>
+@end
+
+@implementation _YYXMLDictionaryParser {
+    NSMutableDictionary *_root;
+    NSMutableArray *_stack;
+    NSMutableString *_text;
+}
+
+- (instancetype)initWithData:(NSData *)data {
+    self = super.init;
+    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
+    [parser setDelegate:self];
+    [parser parse];
+    return self;
+}
+
+- (instancetype)initWithString:(NSString *)xml {
+    NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
+    return [self initWithData:data];
+}
+
+- (NSDictionary *)result {
+    return _root;
+}
+
+#pragma mark - NSXMLParserDelegate
+
+#define XMLText @"_text"
+#define XMLName @"_name"
+#define XMLPref @"_"
+
+- (void)textEnd {
+    _text = _text.stringByTrim.mutableCopy;
+    if (_text.length) {
+        NSMutableDictionary *top = _stack.lastObject;
+        id existing = top[XMLText];
+        if ([existing isKindOfClass:[NSArray class]]) {
+            [existing addObject:_text];
+        } else if (existing) {
+            top[XMLText] = [@[existing, _text] mutableCopy];
+        } else {
+            top[XMLText] = _text;
+        }
+    }
+    _text = nil;
+}
+
+- (void)parser:(__unused NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(__unused NSString *)namespaceURI qualifiedName:(__unused NSString *)qName attributes:(NSDictionary *)attributeDict {
+    [self textEnd];
+    
+    NSMutableDictionary *node = [NSMutableDictionary new];
+    if (!_root) node[XMLName] = elementName;
+    if (attributeDict.count) [node addEntriesFromDictionary:attributeDict];
+    
+    if (_root) {
+        NSMutableDictionary *top = _stack.lastObject;
+        id existing = top[elementName];
+        if ([existing isKindOfClass:[NSArray class]]) {
+            [existing addObject:node];
+        } else if (existing) {
+            top[elementName] = [@[existing, node] mutableCopy];
+        } else {
+            top[elementName] = node;
+        }
+        [_stack addObject:node];
+    } else {
+        _root = node;
+        _stack = [NSMutableArray arrayWithObject:node];
+    }
+}
+
+- (void)parser:(__unused NSXMLParser *)parser didEndElement:(__unused NSString *)elementName namespaceURI:(__unused NSString *)namespaceURI qualifiedName:(__unused NSString *)qName {
+    [self textEnd];
+    
+    NSMutableDictionary *top = _stack.lastObject;
+    [_stack removeLastObject];
+    
+    NSMutableDictionary *left = top.mutableCopy;
+    [left removeObjectsForKeys:@[XMLText, XMLName]];
+    for (NSString *key in left.allKeys) {
+        [left removeObjectForKey:key];
+        if ([key hasPrefix:XMLPref]) {
+            left[[key substringFromIndex:XMLPref.length]] = top[key];
+        }
+    }
+    if (left.count) return;
+    
+    NSMutableDictionary *children = top.mutableCopy;
+    [children removeObjectsForKeys:@[XMLText, XMLName]];
+    for (NSString *key in children.allKeys) {
+        if ([key hasPrefix:XMLPref]) {
+            [children removeObjectForKey:key];
+        }
+    }
+    if (children.count) return;
+    
+    NSMutableDictionary *topNew = _stack.lastObject;
+    NSString *nodeName = top[XMLName];
+    if (!nodeName) {
+        for (NSString *name in topNew) {
+            id object = topNew[name];
+            if (object == top) {
+                nodeName = name; break;
+            } else if ([object isKindOfClass:[NSArray class]] && [object containsObject:top]) {
+                nodeName = name; break;
+            }
+        }
+    }
+    if (!nodeName) return;
+    
+    id inner = top[XMLText];
+    if ([inner isKindOfClass:[NSArray class]]) {
+        inner = [inner componentsJoinedByString:@"\n"];
+    }
+    if (!inner) return;
+    
+    id parent = topNew[nodeName];
+    if ([parent isKindOfClass:[NSArray class]]) {
+        NSArray *parentAsArray = parent;
+        parent[parentAsArray.count - 1] = inner;
+    } else {
+        topNew[nodeName] = inner;
+    }
+}
+
+- (void)parser:(__unused NSXMLParser *)parser foundCharacters:(NSString *)string {
+    if (_text) [_text appendString:string];
+    else _text = [NSMutableString stringWithString:string];
+}
+
+- (void)parser:(__unused NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock {
+    NSString *string = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
+    if (_text) [_text appendString:string];
+    else _text = [NSMutableString stringWithString:string];
+}
+
+#undef XMLText
+#undef XMLName
+#undef XMLPref
+@end
+
+
+@implementation NSDictionary (YYAdd)
+
++ (NSDictionary *)dictionaryWithPlistData:(NSData *)plist {
+    if (!plist) return nil;
+    NSDictionary *dictionary = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListImmutable format:NULL error:NULL];
+    if ([dictionary isKindOfClass:[NSDictionary class]]) return dictionary;
+    return nil;
+}
+
++ (NSDictionary *)dictionaryWithPlistString:(NSString *)plist {
+    if (!plist) return nil;
+    NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
+    return [self dictionaryWithPlistData:data];
+}
+
+- (NSData *)plistData {
+    return [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListBinaryFormat_v1_0 options:kNilOptions error:NULL];
+}
+
+- (NSString *)plistString {
+    NSData *xmlData = [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListXMLFormat_v1_0 options:kNilOptions error:NULL];
+    if (xmlData) return xmlData.utf8String;
+    return nil;
+}
+
+- (NSArray *)allKeysSorted {
+    return [[self allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
+}
+
+- (NSArray *)allValuesSortedByKeys {
+    NSArray *sortedKeys = [self allKeysSorted];
+    NSMutableArray *arr = [[NSMutableArray alloc] init];
+    for (id key in sortedKeys) {
+        [arr addObject:self[key]];
+    }
+    return [arr copy];
+}
+
+- (BOOL)containsObjectForKey:(id)key {
+    if (!key) return NO;
+    return self[key] != nil;
+}
+
+- (NSDictionary *)entriesForKeys:(NSArray *)keys {
+    NSMutableDictionary *dic = [NSMutableDictionary new];
+    for (id key in keys) {
+        id value = self[key];
+        if (value) dic[key] = value;
+    }
+    return [dic copy];
+}
+
+- (NSString *)jsonStringEncoded {
+    if ([NSJSONSerialization isValidJSONObject:self]) {
+        NSError *error;
+        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
+        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
+        if (!error) return json;
+    }
+    return nil;
+}
+
+- (NSString *)jsonPrettyStringEncoded {
+    if ([NSJSONSerialization isValidJSONObject:self]) {
+        NSError *error;
+        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
+        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
+        if (!error) return json;
+    }
+    return nil;
+}
+
++ (NSDictionary *)dictionaryWithXML:(id)xml {
+    _YYXMLDictionaryParser *parser = nil;
+    if ([xml isKindOfClass:[NSString class]]) {
+        parser = [[_YYXMLDictionaryParser alloc] initWithString:xml];
+    } else if ([xml isKindOfClass:[NSData class]]) {
+        parser = [[_YYXMLDictionaryParser alloc] initWithData:xml];
+    }
+    return [parser result];
+}
+
+
+/// Get a number value from 'id'.
+static NSNumber *NSNumberFromID(id value) {
+    static NSCharacterSet *dot;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        dot = [NSCharacterSet characterSetWithRange:NSMakeRange('.', 1)];
+    });
+    if (!value || value == [NSNull null]) return nil;
+    if ([value isKindOfClass:[NSNumber class]]) return value;
+    if ([value isKindOfClass:[NSString class]]) {
+        NSString *lower = ((NSString *)value).lowercaseString;
+        if ([lower isEqualToString:@"true"] || [lower isEqualToString:@"yes"]) return @(YES);
+        if ([lower isEqualToString:@"false"] || [lower isEqualToString:@"no"]) return @(NO);
+        if ([lower isEqualToString:@"nil"] || [lower isEqualToString:@"null"]) return nil;
+        if ([(NSString *)value rangeOfCharacterFromSet:dot].location != NSNotFound) {
+            return @(((NSString *)value).doubleValue);
+        } else {
+            return @(((NSString *)value).longLongValue);
+        }
+    }
+    return nil;
+}
+
+#define RETURN_VALUE(_type_)                                                     \
+if (!key) return def;                                                            \
+id value = self[key];                                                            \
+if (!value || value == [NSNull null]) return def;                                \
+if ([value isKindOfClass:[NSNumber class]]) return ((NSNumber *)value)._type_;   \
+if ([value isKindOfClass:[NSString class]]) return NSNumberFromID(value)._type_; \
+return def;
+
+- (BOOL)boolValueForKey:(NSString *)key default:(BOOL)def {
+    RETURN_VALUE(boolValue);
+}
+
+- (char)charValueForKey:(NSString *)key default:(char)def {
+    RETURN_VALUE(charValue);
+}
+
+- (unsigned char)unsignedCharValueForKey:(NSString *)key default:(unsigned char)def {
+    RETURN_VALUE(unsignedCharValue);
+}
+
+- (short)shortValueForKey:(NSString *)key default:(short)def {
+    RETURN_VALUE(shortValue);
+}
+
+- (unsigned short)unsignedShortValueForKey:(NSString *)key default:(unsigned short)def {
+    RETURN_VALUE(unsignedShortValue);
+}
+
+- (int)intValueForKey:(NSString *)key default:(int)def {
+    RETURN_VALUE(intValue);
+}
+
+- (unsigned int)unsignedIntValueForKey:(NSString *)key default:(unsigned int)def {
+    RETURN_VALUE(unsignedIntValue);
+}
+
+- (long)longValueForKey:(NSString *)key default:(long)def {
+    RETURN_VALUE(longValue);
+}
+
+- (unsigned long)unsignedLongValueForKey:(NSString *)key default:(unsigned long)def {
+    RETURN_VALUE(unsignedLongValue);
+}
+
+- (long long)longLongValueForKey:(NSString *)key default:(long long)def {
+    RETURN_VALUE(longLongValue);
+}
+
+- (unsigned long long)unsignedLongLongValueForKey:(NSString *)key default:(unsigned long long)def {
+    RETURN_VALUE(unsignedLongLongValue);
+}
+
+- (float)floatValueForKey:(NSString *)key default:(float)def {
+    RETURN_VALUE(floatValue);
+}
+
+- (double)doubleValueForKey:(NSString *)key default:(double)def {
+    RETURN_VALUE(doubleValue);
+}
+
+- (NSInteger)integerValueForKey:(NSString *)key default:(NSInteger)def {
+    RETURN_VALUE(integerValue);
+}
+
+- (NSUInteger)unsignedIntegerValueForKey:(NSString *)key default:(NSUInteger)def {
+    RETURN_VALUE(unsignedIntegerValue);
+}
+
+- (NSNumber *)numberValueForKey:(NSString *)key default:(NSNumber *)def {
+    if (!key) return def;
+    id value = self[key];
+    if (!value || value == [NSNull null]) return def;
+    if ([value isKindOfClass:[NSNumber class]]) return value;
+    if ([value isKindOfClass:[NSString class]]) return NSNumberFromID(value);
+    return def;
+}
+
+- (NSString *)stringValueForKey:(NSString *)key default:(NSString *)def {
+    if (!key) return def;
+    id value = self[key];
+    if (!value || value == [NSNull null]) return def;
+    if ([value isKindOfClass:[NSString class]]) return value;
+    if ([value isKindOfClass:[NSNumber class]]) return ((NSNumber *)value).description;
+    return def;
+}
+
+@end
+
+
+@implementation NSMutableDictionary (YYAdd)
+
++ (NSMutableDictionary *)dictionaryWithPlistData:(NSData *)plist {
+    if (!plist) return nil;
+    NSMutableDictionary *dictionary = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListMutableContainersAndLeaves format:NULL error:NULL];
+    if ([dictionary isKindOfClass:[NSMutableDictionary class]]) return dictionary;
+    return nil;
+}
+
++ (NSMutableDictionary *)dictionaryWithPlistString:(NSString *)plist {
+    if (!plist) return nil;
+    NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
+    return [self dictionaryWithPlistData:data];
+}
+
+- (id)popObjectForKey:(id)aKey {
+    if (!aKey) return nil;
+    id value = self[aKey];
+    [self removeObjectForKey:aKey];
+    return value;
+}
+
+- (NSDictionary *)popEntriesForKeys:(NSArray *)keys {
+    NSMutableDictionary *dic = [NSMutableDictionary new];
+    for (id key in keys) {
+        id value = self[key];
+        if (value) {
+            [self removeObjectForKey:key];
+            dic[key] = value;
+        }
+    }
+    return [dic copy];
+}
+
+@end

+ 45 - 0
YYKit/Base/Foundation/NSKeyedUnarchiver+YYAdd.h

@@ -0,0 +1,45 @@
+//
+//  NSKeyedUnarchiver+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/8/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `NSKeyedUnarchiver`.
+ */
+@interface NSKeyedUnarchiver (YYAdd)
+
+/**
+ Same as unarchiveObjectWithData:, except it returns the exception by reference.
+ 
+ @param data       The data need unarchived.
+ 
+ @param exception  Pointer which will, upon return, if an exception occurred and
+ said pointer is not NULL, point to said NSException.
+ */
++ (nullable id)unarchiveObjectWithData:(NSData *)data
+                             exception:(NSException *_Nullable *_Nullable)exception;
+
+/**
+ Same as unarchiveObjectWithFile:, except it returns the exception by reference.
+ 
+ @param path       The path of archived object file.
+ 
+ @param exception  Pointer which will, upon return, if an exception occurred and
+ said  pointer is not NULL, point to said NSException.
+ */
++ (nullable id)unarchiveObjectWithFile:(NSString *)path
+                             exception:(NSException *_Nullable *_Nullable)exception;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 51 - 0
YYKit/Base/Foundation/NSKeyedUnarchiver+YYAdd.m

@@ -0,0 +1,51 @@
+//
+//  NSKeyedUnarchiver+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/8/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSKeyedUnarchiver+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(NSKeyedUnarchiver_YYAdd)
+
+
+@implementation NSKeyedUnarchiver (YYAdd)
+
++ (id)unarchiveObjectWithData:(NSData *)data exception:(__autoreleasing NSException **)exception {
+    id object = nil;
+    @try {
+        object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
+    }
+    @catch (NSException *e)
+    {
+        if (exception) *exception = e;
+    }
+    @finally
+    {
+    }
+    return object;
+}
+
++ (id)unarchiveObjectWithFile:(NSString *)path exception:(__autoreleasing NSException **)exception {
+    id object = nil;
+    
+    @try {
+        object = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
+    }
+    @catch (NSException *e)
+    {
+        if (exception) *exception = e;
+    }
+    @finally
+    {
+    }
+    return object;
+}
+
+@end

+ 97 - 0
YYKit/Base/Foundation/NSNotificationCenter+YYAdd.h

@@ -0,0 +1,97 @@
+//
+//  NSNotificationCenter+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/8/24.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provide some method for `NSNotificationCenter`
+ to post notification in different thread.
+ */
+@interface NSNotificationCenter (YYAdd)
+
+/**
+ Posts a given notification to the receiver on main thread.
+ If current thread is main thread, the notification is posted synchronously;
+ otherwise, is posted asynchronously.
+ 
+ @param notification  The notification to post.
+                      An exception is raised if notification is nil.
+ */
+- (void)postNotificationOnMainThread:(NSNotification *)notification;
+
+/**
+ Posts a given notification to the receiver on main thread.
+ 
+ @param notification The notification to post.
+                     An exception is raised if notification is nil.
+ 
+ @param wait         A Boolean that specifies whether the current thread blocks 
+                     until after the specified notification is posted on the 
+                     receiver on the main thread. Specify YES to block this 
+                     thread; otherwise, specify NO to have this method return 
+                     immediately.
+ */
+- (void)postNotificationOnMainThread:(NSNotification *)notification
+                       waitUntilDone:(BOOL)wait;
+
+/**
+ Creates a notification with a given name and sender and posts it to the 
+ receiver on main thread. If current thread is main thread, the notification 
+ is posted synchronously; otherwise, is posted asynchronously.
+ 
+ @param name    The name of the notification.
+ 
+ @param object  The object posting the notification.
+ */
+- (void)postNotificationOnMainThreadWithName:(NSString *)name
+                                      object:(nullable id)object;
+
+/**
+ Creates a notification with a given name and sender and posts it to the
+ receiver on main thread. If current thread is main thread, the notification
+ is posted synchronously; otherwise, is posted asynchronously.
+ 
+ @param name      The name of the notification.
+ 
+ @param object    The object posting the notification.
+ 
+ @param userInfo  Information about the the notification. May be nil.
+ */
+- (void)postNotificationOnMainThreadWithName:(NSString *)name
+                                      object:(nullable id)object
+                                    userInfo:(nullable NSDictionary *)userInfo;
+
+/**
+ Creates a notification with a given name and sender and posts it to the
+ receiver on main thread.
+ 
+ @param name     The name of the notification.
+ 
+ @param object   The object posting the notification.
+ 
+ @param userInfo Information about the the notification. May be nil.
+ 
+ @param wait     A Boolean that specifies whether the current thread blocks
+                 until after the specified notification is posted on the
+                 receiver on the main thread. Specify YES to block this
+                 thread; otherwise, specify NO to have this method return
+                 immediately.
+ */
+- (void)postNotificationOnMainThreadWithName:(NSString *)name
+                                      object:(nullable id)object
+                                    userInfo:(nullable NSDictionary *)userInfo
+                               waitUntilDone:(BOOL)wait;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 62 - 0
YYKit/Base/Foundation/NSNotificationCenter+YYAdd.m

@@ -0,0 +1,62 @@
+//
+//  NSNotificationCenter+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/8/24.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSNotificationCenter+YYAdd.h"
+#include <pthread.h>
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(NSNotificationCenter_YYAdd)
+
+
+@implementation NSNotificationCenter (YYAdd)
+
+- (void)postNotificationOnMainThread:(NSNotification *)notification {
+    if (pthread_main_np()) return [self postNotification:notification];
+    [self postNotificationOnMainThread:notification waitUntilDone:NO];
+}
+
+- (void)postNotificationOnMainThread:(NSNotification *)notification waitUntilDone:(BOOL)wait {
+    if (pthread_main_np()) return [self postNotification:notification];
+    [[self class] performSelectorOnMainThread:@selector(_yy_postNotification:) withObject:notification waitUntilDone:wait];
+}
+
+- (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object {
+    if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:nil];
+    [self postNotificationOnMainThreadWithName:name object:object userInfo:nil waitUntilDone:NO];
+}
+
+- (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo {
+    if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:userInfo];
+    [self postNotificationOnMainThreadWithName:name object:object userInfo:userInfo waitUntilDone:NO];
+}
+
+- (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo waitUntilDone:(BOOL)wait {
+    if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:userInfo];
+    NSMutableDictionary *info = [[NSMutableDictionary allocWithZone:nil] initWithCapacity:3];
+    if (name) [info setObject:name forKey:@"name"];
+    if (object) [info setObject:object forKey:@"object"];
+    if (userInfo) [info setObject:userInfo forKey:@"userInfo"];
+    [[self class] performSelectorOnMainThread:@selector(_yy_postNotificationName:) withObject:info waitUntilDone:wait];
+}
+
++ (void)_yy_postNotification:(NSNotification *)notification {
+    [[self defaultCenter] postNotification:notification];
+}
+
++ (void)_yy_postNotificationName:(NSDictionary *)info {
+    NSString *name = [info objectForKey:@"name"];
+    id object = [info objectForKey:@"object"];
+    NSDictionary *userInfo = [info objectForKey:@"userInfo"];
+    
+    [[self defaultCenter] postNotificationName:name object:object userInfo:userInfo];
+}
+
+@end

+ 33 - 0
YYKit/Base/Foundation/NSNumber+YYAdd.h

@@ -0,0 +1,33 @@
+//
+//  NSNumber+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/8/24.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provide a method to parse `NSString` for `NSNumber`.
+ */
+@interface NSNumber (YYAdd)
+
+/**
+ Creates and returns an NSNumber object from a string.
+ Valid format: @"12", @"12.345", @" -0xFF", @" .23e99 "...
+ 
+ @param string  The string described an number.
+ 
+ @return an NSNumber when parse succeed, or nil if an error occurs.
+ */
++ (nullable NSNumber *)numberWithString:(NSString *)string;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 63 - 0
YYKit/Base/Foundation/NSNumber+YYAdd.m

@@ -0,0 +1,63 @@
+//
+//  NSNumber+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/8/24.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSNumber+YYAdd.h"
+#import "NSString+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(NSNumber_YYAdd)
+
+
+@implementation NSNumber (YYAdd)
+
++ (NSNumber *)numberWithString:(NSString *)string {
+    NSString *str = [[string stringByTrim] lowercaseString];
+    if (!str || !str.length) {
+        return nil;
+    }
+    
+    static NSDictionary *dic;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        dic = @{@"true" :   @(YES),
+                @"yes" :    @(YES),
+                @"false" :  @(NO),
+                @"no" :     @(NO),
+                @"nil" :    [NSNull null],
+                @"null" :   [NSNull null],
+                @"<null>" : [NSNull null]};
+    });
+    id num = dic[str];
+    if (num) {
+        if (num == [NSNull null]) return nil;
+        return num;
+    }
+    
+    // hex number
+    int sign = 0;
+    if ([str hasPrefix:@"0x"]) sign = 1;
+    else if ([str hasPrefix:@"-0x"]) sign = -1;
+    if (sign != 0) {
+        NSScanner *scan = [NSScanner scannerWithString:str];
+        unsigned num = -1;
+        BOOL suc = [scan scanHexInt:&num];
+        if (suc)
+            return [NSNumber numberWithLong:((long)num * sign)];
+        else
+            return nil;
+    }
+    // normal number
+    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
+    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
+    return [formatter numberFromString:string];
+}
+
+@end

+ 302 - 0
YYKit/Base/Foundation/NSObject+YYAdd.h

@@ -0,0 +1,302 @@
+//
+//  NSObject+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/8.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Common tasks for NSObject.
+ */
+@interface NSObject (YYAdd)
+
+
+#pragma mark - Sending messages with variable parameters
+///=============================================================================
+/// @name Sending messages with variable parameters
+///=============================================================================
+
+/**
+ Sends a specified message to the receiver and returns the result of the message.
+ 
+ @param sel    A selector identifying the message to send. If the selector is
+               NULL or unrecognized, an NSInvalidArgumentException is raised.
+ 
+ @param ...    Variable parameter list. Parameters type must correspond to the
+               selector's method declaration, or unexpected results may occur.
+               It doesn't support union or struct which is larger than 256 bytes.
+ 
+ @return       An object that is the result of the message.
+ 
+ @discussion   The selector's return value will be wrap as NSNumber or NSValue
+               if the selector's `return type` is not object. It always returns nil
+               if the selector's `return type` is void.
+ 
+ Sample Code:
+ 
+     // no variable args
+     [view performSelectorWithArgs:@selector(removeFromSuperView)];
+     
+     // variable arg is not object
+     [view performSelectorWithArgs:@selector(setCenter:), CGPointMake(0, 0)];
+     
+     // perform and return object
+     UIImage *image = [UIImage.class performSelectorWithArgs:@selector(imageWithData:scale:), data, 2.0];
+     
+     // perform and return wrapped number
+     NSNumber *lengthValue = [@"hello" performSelectorWithArgs:@selector(length)];
+     NSUInteger length = lengthValue.unsignedIntegerValue;
+     
+     // perform and return wrapped struct
+     NSValue *frameValue = [view performSelectorWithArgs:@selector(frame)];
+     CGRect frame = frameValue.CGRectValue;
+ */
+- (nullable id)performSelectorWithArgs:(SEL)sel, ...;
+
+/**
+ Invokes a method of the receiver on the current thread using the default mode after a delay.
+ 
+ @warning      It can't cancelled by previous request.
+ 
+ @param sel    A selector identifying the message to send. If the selector is
+               NULL or unrecognized, an NSInvalidArgumentException is raised immediately.
+ 
+ @param delay  The minimum time before which the message is sent. Specifying
+               a delay of 0 does not necessarily cause the selector to be
+               performed immediately. The selector is still queued on the
+               thread's run loop and performed as soon as possible.
+ 
+ @param ...    Variable parameter list. Parameters type must correspond to the
+               selector's method declaration, or unexpected results may occur.
+               It doesn't support union or struct which is larger than 256 bytes.
+ 
+ Sample Code:
+ 
+     // no variable args
+     [view performSelectorWithArgs:@selector(removeFromSuperView) afterDelay:2.0];
+     
+     // variable arg is not object
+     [view performSelectorWithArgs:@selector(setCenter:), afterDelay:0, CGPointMake(0, 0)];
+ */
+- (void)performSelectorWithArgs:(SEL)sel afterDelay:(NSTimeInterval)delay, ...;
+
+/**
+ Invokes a method of the receiver on the main thread using the default mode.
+ 
+ @param sel    A selector identifying the message to send. If the selector is
+               NULL or unrecognized, an NSInvalidArgumentException is raised.
+ 
+ @param wait   A Boolean that specifies whether the current thread blocks until
+               after the specified selector is performed on the receiver on the
+               specified thread. Specify YES to block this thread; otherwise,
+               specify NO to have this method return immediately.
+ 
+ @param ...    Variable parameter list. Parameters type must correspond to the
+               selector's method declaration, or unexpected results may occur.
+               It doesn't support union or struct which is larger than 256 bytes.
+ 
+ @return       While @a wait is YES, it returns object that is the result of
+               the message. Otherwise return nil;
+ 
+ @discussion   The selector's return value will be wrap as NSNumber or NSValue
+               if the selector's `return type` is not object. It always returns nil
+               if the selector's `return type` is void, or @a wait is YES.
+ 
+ Sample Code:
+ 
+     // no variable args
+     [view performSelectorWithArgsOnMainThread:@selector(removeFromSuperView), waitUntilDone:NO];
+     
+     // variable arg is not object
+     [view performSelectorWithArgsOnMainThread:@selector(setCenter:), waitUntilDone:NO, CGPointMake(0, 0)];
+ */
+- (nullable id)performSelectorWithArgsOnMainThread:(SEL)sel waitUntilDone:(BOOL)wait, ...;
+
+/**
+ Invokes a method of the receiver on the specified thread using the default mode.
+ 
+ @param sel    A selector identifying the message to send. If the selector is
+               NULL or unrecognized, an NSInvalidArgumentException is raised.
+ 
+ @param thread The thread on which to execute aSelector.
+ 
+ @param wait   A Boolean that specifies whether the current thread blocks until
+               after the specified selector is performed on the receiver on the
+               specified thread. Specify YES to block this thread; otherwise,
+               specify NO to have this method return immediately.
+ 
+ @param ...    Variable parameter list. Parameters type must correspond to the
+               selector's method declaration, or unexpected results may occur.
+               It doesn't support union or struct which is larger than 256 bytes.
+ 
+ @return       While @a wait is YES, it returns object that is the result of
+               the message. Otherwise return nil;
+ 
+ @discussion   The selector's return value will be wrap as NSNumber or NSValue
+               if the selector's `return type` is not object. It always returns nil
+               if the selector's `return type` is void, or @a wait is YES.
+ 
+ Sample Code:
+ 
+     [view performSelectorWithArgs:@selector(removeFromSuperView) onThread:mainThread waitUntilDone:NO];
+     
+     [array  performSelectorWithArgs:@selector(sortUsingComparator:)
+                            onThread:backgroundThread
+                       waitUntilDone:NO, ^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
+         return [num2 compare:num2];
+     }];
+ */
+- (nullable id)performSelectorWithArgs:(SEL)sel onThread:(NSThread *)thread waitUntilDone:(BOOL)wait, ...;
+
+/**
+ Invokes a method of the receiver on a new background thread.
+ 
+ @param sel    A selector identifying the message to send. If the selector is
+               NULL or unrecognized, an NSInvalidArgumentException is raised.
+ 
+ @param ...    Variable parameter list. Parameters type must correspond to the
+               selector's method declaration, or unexpected results may occur.
+               It doesn't support union or struct which is larger than 256 bytes.
+ 
+ @discussion   This method creates a new thread in your application, putting
+               your application into multithreaded mode if it was not already.
+               The method represented by sel must set up the thread environment
+               just as you would for any other new thread in your program.
+ 
+ Sample Code:
+ 
+     [array  performSelectorWithArgsInBackground:@selector(sortUsingComparator:),
+                ^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
+        return [num2 compare:num2];
+     }];
+ */
+- (void)performSelectorWithArgsInBackground:(SEL)sel, ...;
+
+/**
+ Invokes a method of the receiver on the current thread after a delay.
+ 
+ @warning     arc-performSelector-leaks
+ 
+ @param sel   A selector that identifies the method to invoke. The method should
+              not have a significant return value and should take no argument.
+              If the selector is NULL or unrecognized,
+              an NSInvalidArgumentException is raised after the delay.
+ 
+ @param delay The minimum time before which the message is sent. Specifying a
+              delay of 0 does not necessarily cause the selector to be performed
+              immediately. The selector is still queued on the thread's run loop
+              and performed as soon as possible.
+ 
+ @discussion  This method sets up a timer to perform the aSelector message on
+              the current thread's run loop. The timer is configured to run in
+              the default mode (NSDefaultRunLoopMode). When the timer fires, the
+              thread attempts to dequeue the message from the run loop and
+              perform the selector. It succeeds if the run loop is running and
+              in the default mode; otherwise, the timer waits until the run loop
+              is in the default mode.
+ */
+- (void)performSelector:(SEL)sel afterDelay:(NSTimeInterval)delay;
+
+
+#pragma mark - Swap method (Swizzling)
+///=============================================================================
+/// @name Swap method (Swizzling)
+///=============================================================================
+
+/**
+ Swap two instance method's implementation in one class. Dangerous, be careful.
+ 
+ @param originalSel   Selector 1.
+ @param newSel        Selector 2.
+ @return              YES if swizzling succeed; otherwise, NO.
+ */
++ (BOOL)swizzleInstanceMethod:(SEL)originalSel with:(SEL)newSel;
+
+/**
+ Swap two class method's implementation in one class. Dangerous, be careful.
+ 
+ @param originalSel   Selector 1.
+ @param newSel        Selector 2.
+ @return              YES if swizzling succeed; otherwise, NO.
+ */
++ (BOOL)swizzleClassMethod:(SEL)originalSel with:(SEL)newSel;
+
+
+#pragma mark - Associate value
+///=============================================================================
+/// @name Associate value
+///=============================================================================
+
+/**
+ Associate one object to `self`, as if it was a strong property (strong, nonatomic).
+ 
+ @param value   The object to associate.
+ @param key     The pointer to get value from `self`.
+ */
+- (void)setAssociateValue:(nullable id)value withKey:(void *)key;
+
+/**
+ Associate one object to `self`, as if it was a weak property (week, nonatomic).
+ 
+ @param value  The object to associate.
+ @param key    The pointer to get value from `self`.
+ */
+- (void)setAssociateWeakValue:(nullable id)value withKey:(void *)key;
+
+/**
+ Get the associated value from `self`.
+ 
+ @param key The pointer to get value from `self`.
+ */
+- (nullable id)getAssociatedValueForKey:(void *)key;
+
+/**
+ Remove all associated values.
+ */
+- (void)removeAssociatedValues;
+
+
+#pragma mark - Others
+///=============================================================================
+/// @name Others
+///=============================================================================
+
+/**
+ Returns the class name in NSString.
+ */
++ (NSString *)className;
+
+/**
+ Returns the class name in NSString.
+ 
+ @discussion Apple has implemented this method in NSObject(NSLayoutConstraintCallsThis),
+ but did not make it public.
+ */
+- (NSString *)className;
+
+/**
+ Returns a copy of the instance with `NSKeyedArchiver` and ``NSKeyedUnarchiver``.
+ Returns nil if an error occurs.
+ */
+- (nullable id)deepCopy;
+
+/**
+ Returns a copy of the instance use archiver and unarchiver.
+ Returns nil if an error occurs.
+ 
+ @param archiver   NSKeyedArchiver class or any class inherited.
+ @param unarchiver NSKeyedUnarchiver clsas or any class inherited.
+ */
+- (nullable id)deepCopyWithArchiver:(Class)archiver unarchiver:(Class)unarchiver;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 396 - 0
YYKit/Base/Foundation/NSObject+YYAdd.m

@@ -0,0 +1,396 @@
+//
+//  NSObject+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/8.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSObject+YYAdd.h"
+#import "YYKitMacro.h"
+#import <objc/objc.h>
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(NSObject_YYAdd)
+
+
+@implementation NSObject (YYAdd)
+
+/*
+ NSInvocation is much slower than objc_msgSend()...
+ Do not use it if you have performance issues.
+ */
+
+#define INIT_INV(_last_arg_, _return_) \
+NSMethodSignature * sig = [self methodSignatureForSelector:sel]; \
+if (!sig) { [self doesNotRecognizeSelector:sel]; return _return_; } \
+NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig]; \
+if (!inv) { [self doesNotRecognizeSelector:sel]; return _return_; } \
+[inv setTarget:self]; \
+[inv setSelector:sel]; \
+va_list args; \
+va_start(args, _last_arg_); \
+[NSObject setInv:inv withSig:sig andArgs:args]; \
+va_end(args);
+
+- (id)performSelectorWithArgs:(SEL)sel, ...{
+    INIT_INV(sel, nil);
+    [inv invoke];
+    return [NSObject getReturnFromInv:inv withSig:sig];
+}
+
+- (void)performSelectorWithArgs:(SEL)sel afterDelay:(NSTimeInterval)delay, ...{
+    INIT_INV(delay, );
+    [inv retainArguments];
+    [inv performSelector:@selector(invoke) withObject:nil afterDelay:delay];
+}
+
+- (id)performSelectorWithArgsOnMainThread:(SEL)sel waitUntilDone:(BOOL)wait, ...{
+    INIT_INV(wait, nil);
+    if (!wait) [inv retainArguments];
+    [inv performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:wait];
+    return wait ? [NSObject getReturnFromInv:inv withSig:sig] : nil;
+}
+
+- (id)performSelectorWithArgs:(SEL)sel onThread:(NSThread *)thr waitUntilDone:(BOOL)wait, ...{
+    INIT_INV(wait, nil);
+    if (!wait) [inv retainArguments];
+    [inv performSelector:@selector(invoke) onThread:thr withObject:nil waitUntilDone:wait];
+    return wait ? [NSObject getReturnFromInv:inv withSig:sig] : nil;
+}
+
+- (void)performSelectorWithArgsInBackground:(SEL)sel, ...{
+    INIT_INV(sel, );
+    [inv retainArguments];
+    [inv performSelectorInBackground:@selector(invoke) withObject:nil];
+}
+
+#undef INIT_INV
+
++ (id)getReturnFromInv:(NSInvocation *)inv withSig:(NSMethodSignature *)sig {
+    NSUInteger length = [sig methodReturnLength];
+    if (length == 0) return nil;
+    
+    char *type = (char *)[sig methodReturnType];
+    while (*type == 'r' || // const
+           *type == 'n' || // in
+           *type == 'N' || // inout
+           *type == 'o' || // out
+           *type == 'O' || // bycopy
+           *type == 'R' || // byref
+           *type == 'V') { // oneway
+        type++; // cutoff useless prefix
+    }
+    
+#define return_with_number(_type_) \
+do { \
+_type_ ret; \
+[inv getReturnValue:&ret]; \
+return @(ret); \
+} while (0)
+    
+    switch (*type) {
+        case 'v': return nil; // void
+        case 'B': return_with_number(bool);
+        case 'c': return_with_number(char);
+        case 'C': return_with_number(unsigned char);
+        case 's': return_with_number(short);
+        case 'S': return_with_number(unsigned short);
+        case 'i': return_with_number(int);
+        case 'I': return_with_number(unsigned int);
+        case 'l': return_with_number(int);
+        case 'L': return_with_number(unsigned int);
+        case 'q': return_with_number(long long);
+        case 'Q': return_with_number(unsigned long long);
+        case 'f': return_with_number(float);
+        case 'd': return_with_number(double);
+        case 'D': { // long double
+            long double ret;
+            [inv getReturnValue:&ret];
+            return [NSNumber numberWithDouble:ret];
+        };
+            
+        case '@': { // id
+            id ret = nil;
+            [inv getReturnValue:&ret];
+            return ret;
+        };
+            
+        case '#': { // Class
+            Class ret = nil;
+            [inv getReturnValue:&ret];
+            return ret;
+        };
+            
+        default: { // struct / union / SEL / void* / unknown
+            const char *objCType = [sig methodReturnType];
+            char *buf = calloc(1, length);
+            if (!buf) return nil;
+            [inv getReturnValue:buf];
+            NSValue *value = [NSValue valueWithBytes:buf objCType:objCType];
+            free(buf);
+            return value;
+        };
+    }
+#undef return_with_number
+}
+
++ (void)setInv:(NSInvocation *)inv withSig:(NSMethodSignature *)sig andArgs:(va_list)args {
+    NSUInteger count = [sig numberOfArguments];
+    for (int index = 2; index < count; index++) {
+        char *type = (char *)[sig getArgumentTypeAtIndex:index];
+        while (*type == 'r' || // const
+               *type == 'n' || // in
+               *type == 'N' || // inout
+               *type == 'o' || // out
+               *type == 'O' || // bycopy
+               *type == 'R' || // byref
+               *type == 'V') { // oneway
+            type++; // cutoff useless prefix
+        }
+        
+        BOOL unsupportedType = NO;
+        switch (*type) {
+            case 'v': // 1: void
+            case 'B': // 1: bool
+            case 'c': // 1: char / BOOL
+            case 'C': // 1: unsigned char
+            case 's': // 2: short
+            case 'S': // 2: unsigned short
+            case 'i': // 4: int / NSInteger(32bit)
+            case 'I': // 4: unsigned int / NSUInteger(32bit)
+            case 'l': // 4: long(32bit)
+            case 'L': // 4: unsigned long(32bit)
+            { // 'char' and 'short' will be promoted to 'int'.
+                int arg = va_arg(args, int);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case 'q': // 8: long long / long(64bit) / NSInteger(64bit)
+            case 'Q': // 8: unsigned long long / unsigned long(64bit) / NSUInteger(64bit)
+            {
+                long long arg = va_arg(args, long long);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case 'f': // 4: float / CGFloat(32bit)
+            { // 'float' will be promoted to 'double'.
+                double arg = va_arg(args, double);
+                float argf = arg;
+                [inv setArgument:&argf atIndex:index];
+            } break;
+                
+            case 'd': // 8: double / CGFloat(64bit)
+            {
+                double arg = va_arg(args, double);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case 'D': // 16: long double
+            {
+                long double arg = va_arg(args, long double);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case '*': // char *
+            case '^': // pointer
+            {
+                void *arg = va_arg(args, void *);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case ':': // SEL
+            {
+                SEL arg = va_arg(args, SEL);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case '#': // Class
+            {
+                Class arg = va_arg(args, Class);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case '@': // id
+            {
+                id arg = va_arg(args, id);
+                [inv setArgument:&arg atIndex:index];
+            } break;
+                
+            case '{': // struct
+            {
+                if (strcmp(type, @encode(CGPoint)) == 0) {
+                    CGPoint arg = va_arg(args, CGPoint);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(CGSize)) == 0) {
+                    CGSize arg = va_arg(args, CGSize);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(CGRect)) == 0) {
+                    CGRect arg = va_arg(args, CGRect);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(CGVector)) == 0) {
+                    CGVector arg = va_arg(args, CGVector);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(CGAffineTransform)) == 0) {
+                    CGAffineTransform arg = va_arg(args, CGAffineTransform);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(CATransform3D)) == 0) {
+                    CATransform3D arg = va_arg(args, CATransform3D);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(NSRange)) == 0) {
+                    NSRange arg = va_arg(args, NSRange);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(UIOffset)) == 0) {
+                    UIOffset arg = va_arg(args, UIOffset);
+                    [inv setArgument:&arg atIndex:index];
+                } else if (strcmp(type, @encode(UIEdgeInsets)) == 0) {
+                    UIEdgeInsets arg = va_arg(args, UIEdgeInsets);
+                    [inv setArgument:&arg atIndex:index];
+                } else {
+                    unsupportedType = YES;
+                }
+            } break;
+                
+            case '(': // union
+            {
+                unsupportedType = YES;
+            } break;
+                
+            case '[': // array
+            {
+                unsupportedType = YES;
+            } break;
+                
+            default: // what?!
+            {
+                unsupportedType = YES;
+            } break;
+        }
+        
+        if (unsupportedType) {
+            // Try with some dummy type...
+            
+            NSUInteger size = 0;
+            NSGetSizeAndAlignment(type, &size, NULL);
+            
+#define case_size(_size_) \
+else if (size <= 4 * _size_ ) { \
+    struct dummy { char tmp[4 * _size_]; }; \
+    struct dummy arg = va_arg(args, struct dummy); \
+    [inv setArgument:&arg atIndex:index]; \
+}
+            if (size == 0) { }
+            case_size( 1) case_size( 2) case_size( 3) case_size( 4)
+            case_size( 5) case_size( 6) case_size( 7) case_size( 8)
+            case_size( 9) case_size(10) case_size(11) case_size(12)
+            case_size(13) case_size(14) case_size(15) case_size(16)
+            case_size(17) case_size(18) case_size(19) case_size(20)
+            case_size(21) case_size(22) case_size(23) case_size(24)
+            case_size(25) case_size(26) case_size(27) case_size(28)
+            case_size(29) case_size(30) case_size(31) case_size(32)
+            case_size(33) case_size(34) case_size(35) case_size(36)
+            case_size(37) case_size(38) case_size(39) case_size(40)
+            case_size(41) case_size(42) case_size(43) case_size(44)
+            case_size(45) case_size(46) case_size(47) case_size(48)
+            case_size(49) case_size(50) case_size(51) case_size(52)
+            case_size(53) case_size(54) case_size(55) case_size(56)
+            case_size(57) case_size(58) case_size(59) case_size(60)
+            case_size(61) case_size(62) case_size(63) case_size(64)
+            else {
+                /*
+                 Larger than 256 byte?! I don't want to deal with this stuff up...
+                 Ignore this argument.
+                 */
+                struct dummy {char tmp;};
+                for (int i = 0; i < size; i++) va_arg(args, struct dummy);
+                NSLog(@"YYKit performSelectorWithArgs unsupported type:%s (%lu bytes)",
+                      [sig getArgumentTypeAtIndex:index],(unsigned long)size);
+            }
+#undef case_size
+
+        }
+    }
+}
+
+- (void)performSelector:(SEL)sel afterDelay:(NSTimeInterval)delay {
+    [self performSelector:sel withObject:nil afterDelay:delay];
+}
+
++ (BOOL)swizzleInstanceMethod:(SEL)originalSel with:(SEL)newSel {
+    Method originalMethod = class_getInstanceMethod(self, originalSel);
+    Method newMethod = class_getInstanceMethod(self, newSel);
+    if (!originalMethod || !newMethod) return NO;
+    
+    class_addMethod(self,
+                    originalSel,
+                    class_getMethodImplementation(self, originalSel),
+                    method_getTypeEncoding(originalMethod));
+    class_addMethod(self,
+                    newSel,
+                    class_getMethodImplementation(self, newSel),
+                    method_getTypeEncoding(newMethod));
+    
+    method_exchangeImplementations(class_getInstanceMethod(self, originalSel),
+                                   class_getInstanceMethod(self, newSel));
+    return YES;
+}
+
++ (BOOL)swizzleClassMethod:(SEL)originalSel with:(SEL)newSel {
+    Class class = object_getClass(self);
+    Method originalMethod = class_getInstanceMethod(class, originalSel);
+    Method newMethod = class_getInstanceMethod(class, newSel);
+    if (!originalMethod || !newMethod) return NO;
+    method_exchangeImplementations(originalMethod, newMethod);
+    return YES;
+}
+
+- (void)setAssociateValue:(id)value withKey:(void *)key {
+    objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (void)setAssociateWeakValue:(id)value withKey:(void *)key {
+    objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_ASSIGN);
+}
+
+- (void)removeAssociatedValues {
+    objc_removeAssociatedObjects(self);
+}
+
+- (id)getAssociatedValueForKey:(void *)key {
+    return objc_getAssociatedObject(self, key);
+}
+
++ (NSString *)className {
+    return NSStringFromClass(self);
+}
+
+- (NSString *)className {
+    return [NSString stringWithUTF8String:class_getName([self class])];
+}
+
+- (id)deepCopy {
+    id obj = nil;
+    @try {
+        obj = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self]];
+    }
+    @catch (NSException *exception) {
+        NSLog(@"%@", exception);
+    }
+    return obj;
+}
+
+- (id)deepCopyWithArchiver:(Class)archiver unarchiver:(Class)unarchiver {
+    id obj = nil;
+    @try {
+        obj = [unarchiver unarchiveObjectWithData:[archiver archivedDataWithRootObject:self]];
+    }
+    @catch (NSException *exception) {
+        NSLog(@"%@", exception);
+    }
+    return obj;
+}
+
+@end

+ 31 - 0
YYKit/Base/Foundation/NSObject+YYAddForARC.h

@@ -0,0 +1,31 @@
+//
+//  NSObject+YYAddForARC.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/12/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+/**
+ Debug method for NSObject when using ARC.
+ */
+@interface NSObject (YYAddForARC)
+
+/// Same as `retain`
+- (instancetype)arcDebugRetain;
+
+/// Same as `release`
+- (oneway void)arcDebugRelease;
+
+/// Same as `autorelease`
+- (instancetype)arcDebugAutorelease;
+
+/// Same as `retainCount`
+- (NSUInteger)arcDebugRetainCount;
+
+@end

+ 40 - 0
YYKit/Base/Foundation/NSObject+YYAddForARC.m

@@ -0,0 +1,40 @@
+//
+//  NSObject+YYAddForARC.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/12/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSObject+YYAddForARC.h"
+
+@interface NSObject_YYAddForARC : NSObject @end
+@implementation NSObject_YYAddForARC @end
+
+#if __has_feature(objc_arc)
+#error This file must be compiled without ARC. Specify the -fno-objc-arc flag to this file.
+#endif
+
+
+@implementation NSObject (YYAddForARC)
+
+- (instancetype)arcDebugRetain {
+    return [self retain];
+}
+
+- (oneway void)arcDebugRelease {
+    [self release];
+}
+
+- (instancetype)arcDebugAutorelease {
+    return [self autorelease];
+}
+
+- (NSUInteger)arcDebugRetainCount {
+    return [self retainCount];
+}
+
+@end

+ 53 - 0
YYKit/Base/Foundation/NSObject+YYAddForKVO.h

@@ -0,0 +1,53 @@
+//
+//  NSObject+YYAddForKVO.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Observer with block (KVO).
+ */
+@interface NSObject (YYAddForKVO)
+
+/**
+ Registers a block to receive KVO notifications for the specified key-path 
+ relative to the receiver.
+ 
+ @discussion The block and block captured objects are retained. Call
+ `removeObserverBlocksForKeyPath:` or `removeObserverBlocks` to release.
+ 
+ @param keyPath The key path, relative to the receiver, of the property to 
+ observe. This value must not be nil.
+ 
+ @param block   The block to register for KVO notifications.
+ */
+- (void)addObserverBlockForKeyPath:(NSString*)keyPath block:(void (^)(id _Nonnull obj, _Nullable id oldVal, _Nullable id newVal))block;
+
+/**
+ Stops all blocks (associated by `addObserverBlockForKeyPath:block:`) from
+ receiving change notifications for the property specified by a given key-path 
+ relative to the receiver, and release these blocks.
+ 
+ @param keyPath A key-path, relative to the receiver, for which blocks is 
+ registered to receive KVO change notifications.
+ */
+- (void)removeObserverBlocksForKeyPath:(NSString*)keyPath;
+
+/**
+ Stops all blocks (associated by `addObserverBlockForKeyPath:block:`) from
+ receiving change notifications, and release these blocks.
+ */
+- (void)removeObserverBlocks;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 110 - 0
YYKit/Base/Foundation/NSObject+YYAddForKVO.m

@@ -0,0 +1,110 @@
+//
+//  NSObject+YYAddForKVO.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSObject+YYAddForKVO.h"
+#import "YYKitMacro.h"
+#import <objc/objc.h>
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(NSObject_YYAddForKVO)
+
+
+
+
+static const int block_key;
+
+@interface _YYNSObjectKVOBlockTarget : NSObject
+
+@property (nonatomic, copy) void (^block)(__weak id obj, id oldVal, id newVal);
+
+- (id)initWithBlock:(void (^)(__weak id obj, id oldVal, id newVal))block;
+
+@end
+
+@implementation _YYNSObjectKVOBlockTarget
+
+- (id)initWithBlock:(void (^)(__weak id obj, id oldVal, id newVal))block {
+    self = [super init];
+    if (self) {
+        self.block = block;
+    }
+    return self;
+}
+
+- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
+    if (!self.block) return;
+    
+    BOOL isPrior = [[change objectForKey:NSKeyValueChangeNotificationIsPriorKey] boolValue];
+    if (isPrior) return;
+    
+    NSKeyValueChange changeKind = [[change objectForKey:NSKeyValueChangeKindKey] integerValue];
+    if (changeKind != NSKeyValueChangeSetting) return;
+    
+    id oldVal = [change objectForKey:NSKeyValueChangeOldKey];
+    if (oldVal == [NSNull null]) oldVal = nil;
+    
+    id newVal = [change objectForKey:NSKeyValueChangeNewKey];
+    if (newVal == [NSNull null]) newVal = nil;
+    
+    self.block(object, oldVal, newVal);
+}
+
+@end
+
+
+
+@implementation NSObject (YYAddForKVO)
+
+- (void)addObserverBlockForKeyPath:(NSString *)keyPath block:(void (^)(__weak id obj, id oldVal, id newVal))block {
+    if (!keyPath || !block) return;
+    _YYNSObjectKVOBlockTarget *target = [[_YYNSObjectKVOBlockTarget alloc] initWithBlock:block];
+    NSMutableDictionary *dic = [self _yy_allNSObjectObserverBlocks];
+    NSMutableArray *arr = dic[keyPath];
+    if (!arr) {
+        arr = [NSMutableArray new];
+        dic[keyPath] = arr;
+    }
+    [arr addObject:target];
+    [self addObserver:target forKeyPath:keyPath options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
+}
+
+- (void)removeObserverBlocksForKeyPath:(NSString *)keyPath {
+    if (!keyPath) return;
+    NSMutableDictionary *dic = [self _yy_allNSObjectObserverBlocks];
+    NSMutableArray *arr = dic[keyPath];
+    [arr enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
+        [self removeObserver:obj forKeyPath:keyPath];
+    }];
+    
+    [dic removeObjectForKey:keyPath];
+}
+
+- (void)removeObserverBlocks {
+    NSMutableDictionary *dic = [self _yy_allNSObjectObserverBlocks];
+    [dic enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSArray *arr, BOOL *stop) {
+        [arr enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
+            [self removeObserver:obj forKeyPath:key];
+        }];
+    }];
+    
+    [dic removeAllObjects];
+}
+
+- (NSMutableDictionary *)_yy_allNSObjectObserverBlocks {
+    NSMutableDictionary *targets = objc_getAssociatedObject(self, &block_key);
+    if (!targets) {
+        targets = [NSMutableDictionary new];
+        objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return targets;
+}
+
+@end

+ 409 - 0
YYKit/Base/Foundation/NSString+YYAdd.h

@@ -0,0 +1,409 @@
+//
+//  NSString+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provide hash, encrypt, encode and some common method for 'NSString'.
+ */
+@interface NSString (YYAdd)
+
+#pragma mark - Hash
+///=============================================================================
+/// @name Hash
+///=============================================================================
+
+/**
+ Returns a lowercase NSString for md2 hash.
+ */
+- (nullable NSString *)md2String;
+
+/**
+ Returns a lowercase NSString for md4 hash.
+ */
+- (nullable NSString *)md4String;
+
+/**
+ Returns a lowercase NSString for md5 hash.
+ */
+- (nullable NSString *)md5String;
+
+/**
+ Returns a lowercase NSString for sha1 hash.
+ */
+- (nullable NSString *)sha1String;
+
+/**
+ Returns a lowercase NSString for sha224 hash.
+ */
+- (nullable NSString *)sha224String;
+
+/**
+ Returns a lowercase NSString for sha256 hash.
+ */
+- (nullable NSString *)sha256String;
+
+/**
+ Returns a lowercase NSString for sha384 hash.
+ */
+- (nullable NSString *)sha384String;
+
+/**
+ Returns a lowercase NSString for sha512 hash.
+ */
+- (nullable NSString *)sha512String;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm md5 with key.
+ @param key The hmac key.
+ */
+- (nullable NSString *)hmacMD5StringWithKey:(NSString *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha1 with key.
+ @param key The hmac key.
+ */
+- (nullable NSString *)hmacSHA1StringWithKey:(NSString *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha224 with key.
+ @param key The hmac key.
+ */
+- (nullable NSString *)hmacSHA224StringWithKey:(NSString *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha256 with key.
+ @param key The hmac key.
+ */
+- (nullable NSString *)hmacSHA256StringWithKey:(NSString *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha384 with key.
+ @param key The hmac key.
+ */
+- (nullable NSString *)hmacSHA384StringWithKey:(NSString *)key;
+
+/**
+ Returns a lowercase NSString for hmac using algorithm sha512 with key.
+ @param key The hmac key.
+ */
+- (nullable NSString *)hmacSHA512StringWithKey:(NSString *)key;
+
+/**
+ Returns a lowercase NSString for crc32 hash.
+ */
+- (nullable NSString *)crc32String;
+
+
+#pragma mark - Encode and decode
+///=============================================================================
+/// @name Encode and decode
+///=============================================================================
+
+/**
+ Returns an NSString for base64 encoded.
+ */
+- (nullable NSString *)base64EncodedString;
+
+/**
+ Returns an NSString from base64 encoded string.
+ @param base64Encoding The encoded string.
+ */
++ (nullable NSString *)stringWithBase64EncodedString:(NSString *)base64EncodedString;
+
+/**
+ URL encode a string in utf-8.
+ @return the encoded string.
+ */
+- (NSString *)stringByURLEncode;
+
+/**
+ URL decode a string in utf-8.
+ @return the decoded string.
+ */
+- (NSString *)stringByURLDecode;
+
+/**
+ Escape common HTML to Entity.
+ Example: "a<b" will be escape to "a&lt;b".
+ */
+- (NSString *)stringByEscapingHTML;
+
+#pragma mark - Drawing
+///=============================================================================
+/// @name Drawing
+///=============================================================================
+
+/**
+ Returns the size of the string if it were rendered with the specified constraints.
+ 
+ @param font          The font to use for computing the string size.
+ 
+ @param size          The maximum acceptable size for the string. This value is
+ used to calculate where line breaks and wrapping would occur.
+ 
+ @param lineBreakMode The line break options for computing the size of the string.
+ For a list of possible values, see NSLineBreakMode.
+ 
+ @return              The width and height of the resulting string's bounding box.
+ These values may be rounded up to the nearest whole number.
+ */
+- (CGSize)sizeForFont:(UIFont *)font size:(CGSize)size mode:(NSLineBreakMode)lineBreakMode;
+
+/**
+ Returns the width of the string if it were to be rendered with the specified
+ font on a single line.
+ 
+ @param font  The font to use for computing the string width.
+ 
+ @return      The width of the resulting string's bounding box. These values may be
+ rounded up to the nearest whole number.
+ */
+- (CGFloat)widthForFont:(UIFont *)font;
+
+/**
+ Returns the height of the string if it were rendered with the specified constraints.
+ 
+ @param font   The font to use for computing the string size.
+ 
+ @param width  The maximum acceptable width for the string. This value is used
+ to calculate where line breaks and wrapping would occur.
+ 
+ @return       The height of the resulting string's bounding box. These values
+ may be rounded up to the nearest whole number.
+ */
+- (CGFloat)heightForFont:(UIFont *)font width:(CGFloat)width;
+
+
+#pragma mark - Regular Expression
+///=============================================================================
+/// @name Regular Expression
+///=============================================================================
+
+/**
+ Whether it can match the regular expression
+ 
+ @param regex  The regular expression
+ @param options     The matching options to report.
+ @return YES if can match the regex; otherwise, NO.
+ */
+- (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options;
+
+/**
+ Match the regular expression, and executes a given block using each object in the matches.
+ 
+ @param regex    The regular expression
+ @param options  The matching options to report.
+ @param block    The block to apply to elements in the array of matches.
+ The block takes four arguments:
+     match: The match substring.
+     matchRange: The matching options.
+     stop: A reference to a Boolean value. The block can set the value
+         to YES to stop further processing of the array. The stop
+         argument is an out-only argument. You should only ever set
+         this Boolean to YES within the Block.
+ */
+- (void)enumerateRegexMatches:(NSString *)regex
+                      options:(NSRegularExpressionOptions)options
+                   usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block;
+
+/**
+ Returns a new string containing matching regular expressions replaced with the template string.
+ 
+ @param regex       The regular expression
+ @param options     The matching options to report.
+ @param replacement The substitution template used when replacing matching instances.
+ 
+ @return A string with matching regular expressions replaced by the template string.
+ */
+- (NSString *)stringByReplacingRegex:(NSString *)regex
+                             options:(NSRegularExpressionOptions)options
+                          withString:(NSString *)replacement;
+
+
+#pragma mark - NSNumber Compatible
+///=============================================================================
+/// @name NSNumber Compatible
+///=============================================================================
+
+// Now you can use NSString as a NSNumber.
+@property (readonly) char charValue;
+@property (readonly) unsigned char unsignedCharValue;
+@property (readonly) short shortValue;
+@property (readonly) unsigned short unsignedShortValue;
+@property (readonly) unsigned int unsignedIntValue;
+@property (readonly) long longValue;
+@property (readonly) unsigned long unsignedLongValue;
+@property (readonly) unsigned long long unsignedLongLongValue;
+@property (readonly) NSUInteger unsignedIntegerValue;
+
+
+#pragma mark - Utilities
+///=============================================================================
+/// @name Utilities
+///=============================================================================
+
+/**
+ Returns a new UUID NSString
+ e.g. "D1178E50-2A4D-4F1F-9BD3-F6AAB00E06B1"
+ */
++ (NSString *)stringWithUUID;
+
+/**
+ Returns a string containing the characters in a given UTF32Char.
+ 
+ @param char32 A UTF-32 character.
+ @return A new string, or nil if the character is invalid.
+ */
++ (nullable NSString *)stringWithUTF32Char:(UTF32Char)char32;
+
+/**
+ Returns a string containing the characters in a given UTF32Char array.
+ 
+ @param char32 An array of UTF-32 character.
+ @param length The character count in array.
+ @return A new string, or nil if an error occurs.
+ */
++ (nullable NSString *)stringWithUTF32Chars:(const UTF32Char *)char32 length:(NSUInteger)length;
+
+/**
+ Enumerates the unicode characters (UTF-32) in the specified range of the string.
+ 
+ @param range The range within the string to enumerate substrings.
+ @param block The block executed for the enumeration. The block takes four arguments:
+    char32: The unicode character.
+    range: The range in receiver. If the range.length is 1, the character is in BMP;
+        otherwise (range.length is 2) the character is in none-BMP Plane and stored
+        by a surrogate pair in the receiver.
+    stop: A reference to a Boolean value that the block can use to stop the enumeration 
+        by setting *stop = YES; it should not touch *stop otherwise.
+ */
+- (void)enumerateUTF32CharInRange:(NSRange)range usingBlock:(void (^)(UTF32Char char32, NSRange range, BOOL *stop))block;
+
+/**
+ Trim blank characters (space and newline) in head and tail.
+ @return the trimmed string.
+ */
+- (NSString *)stringByTrim;
+
+/**
+ Add scale modifier to the file name (without path extension),
+ From @"name" to @"name@2x".
+ 
+ e.g.
+ <table>
+ <tr><th>Before     </th><th>After(scale:2)</th></tr>
+ <tr><td>"icon"     </td><td>"icon@2x"     </td></tr>
+ <tr><td>"icon "    </td><td>"icon @2x"    </td></tr>
+ <tr><td>"icon.top" </td><td>"icon.top@2x" </td></tr>
+ <tr><td>"/p/name"  </td><td>"/p/name@2x"  </td></tr>
+ <tr><td>"/path/"   </td><td>"/path/"      </td></tr>
+ </table>
+ 
+ @param scale Resource scale.
+ @return String by add scale modifier, or just return if it's not end with file name.
+ */
+- (NSString *)stringByAppendingNameScale:(CGFloat)scale;
+
+/**
+ Add scale modifier to the file path (with path extension),
+ From @"name.png" to @"name@2x.png".
+ 
+ e.g.
+ <table>
+ <tr><th>Before     </th><th>After(scale:2)</th></tr>
+ <tr><td>"icon.png" </td><td>"icon@2x.png" </td></tr>
+ <tr><td>"icon..png"</td><td>"icon.@2x.png"</td></tr>
+ <tr><td>"icon"     </td><td>"icon@2x"     </td></tr>
+ <tr><td>"icon "    </td><td>"icon @2x"    </td></tr>
+ <tr><td>"icon."    </td><td>"icon.@2x"    </td></tr>
+ <tr><td>"/p/name"  </td><td>"/p/name@2x"  </td></tr>
+ <tr><td>"/path/"   </td><td>"/path/"      </td></tr>
+ </table>
+ 
+ @param scale Resource scale.
+ @return String by add scale modifier, or just return if it's not end with file name.
+ */
+- (NSString *)stringByAppendingPathScale:(CGFloat)scale;
+
+/**
+ Return the path scale.
+ 
+ e.g.
+ <table>
+ <tr><th>Path            </th><th>Scale </th></tr>
+ <tr><td>"icon.png"      </td><td>1     </td></tr>
+ <tr><td>"icon@2x.png"   </td><td>2     </td></tr>
+ <tr><td>"icon@2.5x.png" </td><td>2.5   </td></tr>
+ <tr><td>"icon@2x"       </td><td>1     </td></tr>
+ <tr><td>"icon@2x..png"  </td><td>1     </td></tr>
+ <tr><td>"icon@2x.png/"  </td><td>1     </td></tr>
+ </table>
+ */
+- (CGFloat)pathScale;
+
+/**
+ nil, @"", @"  ", @"\n" will Returns NO; otherwise Returns YES.
+ */
+- (BOOL)isNotBlank;
+
+/**
+ Returns YES if the target string is contained within the receiver.
+ @param string A string to test the the receiver.
+ 
+ @discussion Apple has implemented this method in iOS8.
+ */
+- (BOOL)containsString:(NSString *)string;
+
+/**
+ Returns YES if the target CharacterSet is contained within the receiver.
+ @param set  A character set to test the the receiver.
+ */
+- (BOOL)containsCharacterSet:(NSCharacterSet *)set;
+
+/**
+ Try to parse this string and returns an `NSNumber`.
+ @return Returns an `NSNumber` if parse succeed, or nil if an error occurs.
+ */
+- (nullable NSNumber *)numberValue;
+
+/**
+ Returns an NSData using UTF-8 encoding.
+ */
+- (nullable NSData *)dataValue;
+
+/**
+ Returns NSMakeRange(0, self.length).
+ */
+- (NSRange)rangeOfAll;
+
+/**
+ Returns an NSDictionary/NSArray which is decoded from receiver.
+ Returns nil if an error occurs.
+ 
+ e.g. NSString: @"{"name":"a","count":2}"  => NSDictionary: @[@"name":@"a",@"count":@2]
+ */
+- (nullable id)jsonValueDecoded;
+
+/**
+ Create a string from the file in main bundle (similar to [UIImage imageNamed:]).
+ 
+ @param name The file name (in main bundle).
+ 
+ @return A new string create from the file in UTF-8 character encoding.
+ */
++ (nullable NSString *)stringNamed:(NSString *)name;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 414 - 0
YYKit/Base/Foundation/NSString+YYAdd.m

@@ -0,0 +1,414 @@
+//
+//  NSString+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSString+YYAdd.h"
+#import "NSData+YYAdd.h"
+#import "NSNumber+YYAdd.h"
+#import "UIDevice+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(NSString_YYAdd)
+
+
+@implementation NSString (YYAdd)
+
+- (NSString *)md2String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] md2String];
+}
+
+- (NSString *)md4String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] md4String];
+}
+
+- (NSString *)md5String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] md5String];
+}
+
+- (NSString *)sha1String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha1String];
+}
+
+- (NSString *)sha224String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha224String];
+}
+
+- (NSString *)sha256String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha256String];
+}
+
+- (NSString *)sha384String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha384String];
+}
+
+- (NSString *)sha512String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha512String];
+}
+
+- (NSString *)crc32String {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] crc32String];
+}
+
+- (NSString *)hmacMD5StringWithKey:(NSString *)key {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding]
+            hmacMD5StringWithKey:key];
+}
+
+- (NSString *)hmacSHA1StringWithKey:(NSString *)key {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding]
+            hmacSHA1StringWithKey:key];
+}
+
+- (NSString *)hmacSHA224StringWithKey:(NSString *)key {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding]
+            hmacSHA224StringWithKey:key];
+}
+
+- (NSString *)hmacSHA256StringWithKey:(NSString *)key {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding]
+            hmacSHA256StringWithKey:key];
+}
+
+- (NSString *)hmacSHA384StringWithKey:(NSString *)key {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding]
+            hmacSHA384StringWithKey:key];
+}
+
+- (NSString *)hmacSHA512StringWithKey:(NSString *)key {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding]
+            hmacSHA512StringWithKey:key];
+}
+
+- (NSString *)base64EncodedString {
+    return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
+}
+
++ (NSString *)stringWithBase64EncodedString:(NSString *)base64EncodedString {
+    NSData *data = [NSData dataWithBase64EncodedString:base64EncodedString];
+    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
+}
+
+- (NSString *)stringByURLEncode {
+    if ([self respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) {
+        /**
+         AFNetworking/AFURLRequestSerialization.m
+         
+         Returns a percent-escaped string following RFC 3986 for a query string key or value.
+         RFC 3986 states that the following characters are "reserved" characters.
+            - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
+            - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
+         In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
+         query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
+         should be percent-escaped in the query string.
+            - parameter string: The string to be percent-escaped.
+            - returns: The percent-escaped string.
+         */
+        static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
+        static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
+        
+        NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
+        [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
+        static NSUInteger const batchSize = 50;
+        
+        NSUInteger index = 0;
+        NSMutableString *escaped = @"".mutableCopy;
+        
+        while (index < self.length) {
+            NSUInteger length = MIN(self.length - index, batchSize);
+            NSRange range = NSMakeRange(index, length);
+            // To avoid breaking up character sequences such as 👴🏻👮🏽
+            range = [self rangeOfComposedCharacterSequencesForRange:range];
+            NSString *substring = [self substringWithRange:range];
+            NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
+            [escaped appendString:encoded];
+            
+            index += range.length;
+        }
+        return escaped;
+    } else {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+        CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
+        NSString *encoded = (__bridge_transfer NSString *)
+        CFURLCreateStringByAddingPercentEscapes(
+                                                kCFAllocatorDefault,
+                                                (__bridge CFStringRef)self,
+                                                NULL,
+                                                CFSTR("!#$&'()*+,/:;=?@[]"),
+                                                cfEncoding);
+        return encoded;
+#pragma clang diagnostic pop
+    }
+}
+
+- (NSString *)stringByURLDecode {
+    if ([self respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
+        return [self stringByRemovingPercentEncoding];
+    } else {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+        CFStringEncoding en = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
+        NSString *decoded = [self stringByReplacingOccurrencesOfString:@"+"
+                                                            withString:@" "];
+        decoded = (__bridge_transfer NSString *)
+        CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
+                                                                NULL,
+                                                                (__bridge CFStringRef)decoded,
+                                                                CFSTR(""),
+                                                                en);
+        return decoded;
+#pragma clang diagnostic pop
+    }
+}
+
+- (NSString *)stringByEscapingHTML {
+    NSUInteger len = self.length;
+    if (!len) return self;
+    
+    unichar *buf = malloc(sizeof(unichar) * len);
+    if (!buf) return self;
+    [self getCharacters:buf range:NSMakeRange(0, len)];
+    
+    NSMutableString *result = [NSMutableString string];
+    for (int i = 0; i < len; i++) {
+        unichar c = buf[i];
+        NSString *esc = nil;
+        switch (c) {
+            case 34: esc = @"&quot;"; break;
+            case 38: esc = @"&amp;"; break;
+            case 39: esc = @"&apos;"; break;
+            case 60: esc = @"&lt;"; break;
+            case 62: esc = @"&gt;"; break;
+            default: break;
+        }
+        if (esc) {
+            [result appendString:esc];
+        } else {
+            CFStringAppendCharacters((CFMutableStringRef)result, &c, 1);
+        }
+    }
+    free(buf);
+    return result;
+}
+
+- (CGSize)sizeForFont:(UIFont *)font size:(CGSize)size mode:(NSLineBreakMode)lineBreakMode {
+    CGSize result;
+    if (!font) font = [UIFont systemFontOfSize:12];
+    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
+        NSMutableDictionary *attr = [NSMutableDictionary new];
+        attr[NSFontAttributeName] = font;
+        if (lineBreakMode != NSLineBreakByWordWrapping) {
+            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
+            paragraphStyle.lineBreakMode = lineBreakMode;
+            attr[NSParagraphStyleAttributeName] = paragraphStyle;
+        }
+        CGRect rect = [self boundingRectWithSize:size
+                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
+                                      attributes:attr context:nil];
+        result = rect.size;
+    } else {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+        result = [self sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreakMode];
+#pragma clang diagnostic pop
+    }
+    return result;
+}
+
+- (CGFloat)widthForFont:(UIFont *)font {
+    CGSize size = [self sizeForFont:font size:CGSizeMake(HUGE, HUGE) mode:NSLineBreakByWordWrapping];
+    return size.width;
+}
+
+- (CGFloat)heightForFont:(UIFont *)font width:(CGFloat)width {
+    CGSize size = [self sizeForFont:font size:CGSizeMake(width, HUGE) mode:NSLineBreakByWordWrapping];
+    return size.height;
+}
+
+- (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options {
+    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:NULL];
+    if (!pattern) return NO;
+    return ([pattern numberOfMatchesInString:self options:0 range:NSMakeRange(0, self.length)] > 0);
+}
+
+- (void)enumerateRegexMatches:(NSString *)regex
+                      options:(NSRegularExpressionOptions)options
+                   usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block {
+    if (regex.length == 0 || !block) return;
+    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
+    if (!regex) return;
+    [pattern enumerateMatchesInString:self options:kNilOptions range:NSMakeRange(0, self.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
+        block([self substringWithRange:result.range], result.range, stop);
+    }];
+}
+
+- (NSString *)stringByReplacingRegex:(NSString *)regex
+                             options:(NSRegularExpressionOptions)options
+                          withString:(NSString *)replacement; {
+    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
+    if (!pattern) return self;
+    return [pattern stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, [self length]) withTemplate:replacement];
+}
+
+- (char)charValue {
+    return self.numberValue.charValue;
+}
+
+- (unsigned char) unsignedCharValue {
+    return self.numberValue.unsignedCharValue;
+}
+
+- (short) shortValue {
+    return self.numberValue.shortValue;
+}
+
+- (unsigned short) unsignedShortValue {
+    return self.numberValue.unsignedShortValue;
+}
+
+- (unsigned int) unsignedIntValue {
+    return self.numberValue.unsignedIntValue;
+}
+
+- (long) longValue {
+    return self.numberValue.longValue;
+}
+
+- (unsigned long) unsignedLongValue {
+    return self.numberValue.unsignedLongValue;
+}
+
+- (unsigned long long) unsignedLongLongValue {
+    return self.numberValue.unsignedLongLongValue;
+}
+
+- (NSUInteger) unsignedIntegerValue {
+    return self.numberValue.unsignedIntegerValue;
+}
+
+
++ (NSString *)stringWithUUID {
+    CFUUIDRef uuid = CFUUIDCreate(NULL);
+    CFStringRef string = CFUUIDCreateString(NULL, uuid);
+    CFRelease(uuid);
+    return (__bridge_transfer NSString *)string;
+}
+
++ (NSString *)stringWithUTF32Char:(UTF32Char)char32 {
+    char32 = NSSwapHostIntToLittle(char32);
+    return [[NSString alloc] initWithBytes:&char32 length:4 encoding:NSUTF32LittleEndianStringEncoding];
+}
+
++ (NSString *)stringWithUTF32Chars:(const UTF32Char *)char32 length:(NSUInteger)length {
+    return [[NSString alloc] initWithBytes:(const void *)char32
+                                    length:length * 4
+                                  encoding:NSUTF32LittleEndianStringEncoding];
+}
+
+- (void)enumerateUTF32CharInRange:(NSRange)range usingBlock:(void (^)(UTF32Char char32, NSRange range, BOOL *stop))block {
+    NSString *str = self;
+    if (range.location != 0 || range.length != self.length) {
+        str = [self substringWithRange:range];
+    }
+    NSUInteger len = [str lengthOfBytesUsingEncoding:NSUTF32StringEncoding] / 4;
+    UTF32Char *char32 = (UTF32Char *)[str cStringUsingEncoding:NSUTF32LittleEndianStringEncoding];
+    if (len == 0 || char32 == NULL) return;
+    
+    NSUInteger location = 0;
+    BOOL stop = NO;
+    NSRange subRange;
+    UTF32Char oneChar;
+    
+    for (NSUInteger i = 0; i < len; i++) {
+        oneChar = char32[i];
+        subRange = NSMakeRange(location, oneChar > 0xFFFF ? 2 : 1);
+        block(oneChar, subRange, &stop);
+        if (stop) return;
+        location += subRange.length;
+    }
+}
+
+- (NSString *)stringByTrim {
+    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
+    return [self stringByTrimmingCharactersInSet:set];
+}
+
+- (NSString *)stringByAppendingNameScale:(CGFloat)scale {
+    if (fabs(scale - 1) <= __FLT_EPSILON__ || self.length == 0 || [self hasSuffix:@"/"]) return self.copy;
+    return [self stringByAppendingFormat:@"@%@x", @(scale)];
+}
+
+- (NSString *)stringByAppendingPathScale:(CGFloat)scale {
+    if (fabs(scale - 1) <= __FLT_EPSILON__ || self.length == 0 || [self hasSuffix:@"/"]) return self.copy;
+    NSString *ext = self.pathExtension;
+    NSRange extRange = NSMakeRange(self.length - ext.length, 0);
+    if (ext.length > 0) extRange.location -= 1;
+    NSString *scaleStr = [NSString stringWithFormat:@"@%@x", @(scale)];
+    return [self stringByReplacingCharactersInRange:extRange withString:scaleStr];
+}
+
+- (CGFloat)pathScale {
+    if (self.length == 0 || [self hasSuffix:@"/"]) return 1;
+    NSString *name = self.stringByDeletingPathExtension;
+    __block CGFloat scale = 1;
+    [name enumerateRegexMatches:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines usingBlock: ^(NSString *match, NSRange matchRange, BOOL *stop) {
+        scale = [match substringWithRange:NSMakeRange(1, match.length - 2)].doubleValue;
+    }];
+    return scale;
+}
+
+- (BOOL)isNotBlank {
+    NSCharacterSet *blank = [NSCharacterSet whitespaceAndNewlineCharacterSet];
+    for (NSInteger i = 0; i < self.length; ++i) {
+        unichar c = [self characterAtIndex:i];
+        if (![blank characterIsMember:c]) {
+            return YES;
+        }
+    }
+    return NO;
+}
+
+- (BOOL)containsString:(NSString *)string {
+    if (string == nil) return NO;
+    return [self rangeOfString:string].location != NSNotFound;
+}
+
+- (BOOL)containsCharacterSet:(NSCharacterSet *)set {
+    if (set == nil) return NO;
+    return [self rangeOfCharacterFromSet:set].location != NSNotFound;
+}
+
+- (NSNumber *)numberValue {
+    return [NSNumber numberWithString:self];
+}
+
+- (NSData *)dataValue {
+    return [self dataUsingEncoding:NSUTF8StringEncoding];
+}
+
+- (NSRange)rangeOfAll {
+    return NSMakeRange(0, self.length);
+}
+
+- (id)jsonValueDecoded {
+    return [[self dataValue] jsonValueDecoded];
+}
+
++ (NSString *)stringNamed:(NSString *)name {
+    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@""];
+    NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
+    if (!str) {
+        path = [[NSBundle mainBundle] pathForResource:name ofType:@"txt"];
+        str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
+    }
+    return str;
+}
+
+@end

+ 25 - 0
YYKit/Base/Foundation/NSThread+YYAdd.h

@@ -0,0 +1,25 @@
+//
+//  NSThread+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/7/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+@interface NSThread (YYAdd)
+
+/**
+ Add an autorelease pool to current runloop for current thread.
+ 
+ @discussion If you create your own thread (NSThread/pthread), and you use 
+ runloop to manage your task, you may use this method to add an autorelease pool
+ to the runloop. Its behavior is the same as the main thread's autorelease pool.
+ */
++ (void)addAutoreleasePoolToCurrentRunloop;
+
+@end

+ 107 - 0
YYKit/Base/Foundation/NSThread+YYAdd.m

@@ -0,0 +1,107 @@
+//
+//  NSThread+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/7/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSThread+YYAdd.h"
+#import <CoreFoundation/CoreFoundation.h>
+
+@interface NSThread_YYAdd : NSObject @end
+@implementation NSThread_YYAdd @end
+
+#if __has_feature(objc_arc)
+#error This file must be compiled without ARC. Specify the -fno-objc-arc flag to this file.
+#endif
+
+static NSString *const YYNSThreadAutoleasePoolKey = @"YYNSThreadAutoleasePoolKey";
+static NSString *const YYNSThreadAutoleasePoolStackKey = @"YYNSThreadAutoleasePoolStackKey";
+
+static const void *PoolStackRetainCallBack(CFAllocatorRef allocator, const void *value) {
+    return value;
+}
+
+static void PoolStackReleaseCallBack(CFAllocatorRef allocator, const void *value) {
+    CFRelease((CFTypeRef)value);
+}
+
+
+static inline void YYAutoreleasePoolPush() {
+    NSMutableDictionary *dic =  [NSThread currentThread].threadDictionary;
+    NSMutableArray *poolStack = dic[YYNSThreadAutoleasePoolStackKey];
+    
+    if (!poolStack) {
+        /*
+         do not retain pool on push,
+         but release on pop to avoid memory analyze warning
+         */
+        CFArrayCallBacks callbacks = {0};
+        callbacks.retain = PoolStackRetainCallBack;
+        callbacks.release = PoolStackReleaseCallBack;
+        poolStack = (id)CFArrayCreateMutable(CFAllocatorGetDefault(), 0, &callbacks);
+        dic[YYNSThreadAutoleasePoolStackKey] = poolStack;
+        CFRelease(poolStack);
+    }
+    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //< create
+    [poolStack addObject:pool]; // push
+}
+
+static inline void YYAutoreleasePoolPop() {
+    NSMutableDictionary *dic =  [NSThread currentThread].threadDictionary;
+    NSMutableArray *poolStack = dic[YYNSThreadAutoleasePoolStackKey];
+    [poolStack removeLastObject]; // pop
+}
+
+static void YYRunLoopAutoreleasePoolObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
+    switch (activity) {
+        case kCFRunLoopEntry: {
+            YYAutoreleasePoolPush();
+        } break;
+        case kCFRunLoopBeforeWaiting: {
+            YYAutoreleasePoolPop();
+            YYAutoreleasePoolPush();
+        } break;
+        case kCFRunLoopExit: {
+            YYAutoreleasePoolPop();
+        } break;
+        default: break;
+    }
+}
+
+static void YYRunloopAutoreleasePoolSetup() {
+    CFRunLoopRef runloop = CFRunLoopGetCurrent();
+
+    CFRunLoopObserverRef pushObserver;
+    pushObserver = CFRunLoopObserverCreate(CFAllocatorGetDefault(), kCFRunLoopEntry,
+                                           true,         // repeat
+                                           -0x7FFFFFFF,  // before other observers
+                                           YYRunLoopAutoreleasePoolObserverCallBack, NULL);
+    CFRunLoopAddObserver(runloop, pushObserver, kCFRunLoopCommonModes);
+    CFRelease(pushObserver);
+    
+    CFRunLoopObserverRef popObserver;
+    popObserver = CFRunLoopObserverCreate(CFAllocatorGetDefault(), kCFRunLoopBeforeWaiting | kCFRunLoopExit,
+                                          true,        // repeat
+                                          0x7FFFFFFF,  // after other observers
+                                          YYRunLoopAutoreleasePoolObserverCallBack, NULL);
+    CFRunLoopAddObserver(runloop, popObserver, kCFRunLoopCommonModes);
+    CFRelease(popObserver);
+}
+
+@implementation NSThread (YYAdd)
+
++ (void)addAutoreleasePoolToCurrentRunloop {
+    if ([NSThread isMainThread]) return; // The main thread already has autorelease pool.
+    NSThread *thread = [self currentThread];
+    if (!thread) return;
+    if (thread.threadDictionary[YYNSThreadAutoleasePoolKey]) return; // already added
+    YYRunloopAutoreleasePoolSetup();
+    thread.threadDictionary[YYNSThreadAutoleasePoolKey] = YYNSThreadAutoleasePoolKey; // mark the state
+}
+
+@end

+ 66 - 0
YYKit/Base/Foundation/NSTimer+YYAdd.h

@@ -0,0 +1,66 @@
+//
+//  NSTimer+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/15/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `NSTimer`.
+ */
+@interface NSTimer (YYAdd)
+
+/**
+ Creates and returns a new NSTimer object and schedules it on the current run 
+ loop in the default mode.
+ 
+ @discussion     After seconds seconds have elapsed, the timer fires, 
+                 sending the message aSelector to target.
+ 
+ @param seconds  The number of seconds between firings of the timer. If seconds
+                 is less than or equal to 0.0, this method chooses the
+                 nonnegative value of 0.1 milliseconds instead.
+ 
+ @param block    The block to invoke when the timer fires. The timer  maintains
+                 a strong reference to the block until it (the timer) is invalidated.
+
+ @param repeats  If YES, the timer will repeatedly reschedule itself until
+                 invalidated. If NO, the timer will be invalidated after it fires.
+ 
+ @return A new NSTimer object, configured according to the specified parameters.
+ */
++ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats;
+
+/**
+ Creates and returns a new NSTimer object initialized with the specified block.
+ 
+ @discussion      You must add the new timer to a run loop, using addTimer:forMode:. 
+                  Then, after seconds have elapsed, the timer fires, invoking
+                  block. (If the timer is configured to repeat, there is no need
+                  to subsequently re-add the timer to the run loop.)
+ 
+ @param seconds  The number of seconds between firings of the timer. If seconds
+                 is less than or equal to 0.0, this method chooses the
+                 nonnegative value of 0.1 milliseconds instead.
+ 
+ @param block    The block to invoke when the timer fires. The timer instructs
+                 the block to maintain a strong reference to its arguments.
+ 
+ @param repeats  If YES, the timer will repeatedly reschedule itself until
+                 invalidated. If NO, the timer will be invalidated after it fires.
+ 
+ @return A new NSTimer object, configured according to the specified parameters.
+ */
++ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 35 - 0
YYKit/Base/Foundation/NSTimer+YYAdd.m

@@ -0,0 +1,35 @@
+//
+//  NSTimer+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/15/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "NSTimer+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(NSTimer_YYAdd)
+
+
+@implementation NSTimer (YYAdd)
+
++ (void)_yy_ExecBlock:(NSTimer *)timer {
+    if ([timer userInfo]) {
+        void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo];
+        block(timer);
+    }
+}
+
++ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats {
+    return [NSTimer scheduledTimerWithTimeInterval:seconds target:self selector:@selector(_yy_ExecBlock:) userInfo:[block copy] repeats:repeats];
+}
+
++ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats {
+    return [NSTimer timerWithTimeInterval:seconds target:self selector:@selector(_yy_ExecBlock:) userInfo:[block copy] repeats:repeats];
+}
+
+@end

+ 97 - 0
YYKit/Base/Quartz/CALayer+YYAdd.h

@@ -0,0 +1,97 @@
+//
+//  CALayer+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/10.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+#import <QuartzCore/QuartzCore.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `CALayer`.
+ */
+@interface CALayer (YYAdd)
+
+/**
+ Take snapshot without transform, image's size equals to bounds.
+ */
+- (nullable UIImage *)snapshotImage;
+
+/**
+ Take snapshot without transform, PDF's page size equals to bounds.
+ */
+- (nullable NSData *)snapshotPDF;
+
+/**
+ Shortcut to set the layer's shadow
+ 
+ @param color  Shadow Color
+ @param offset Shadow offset
+ @param radius Shadow radius
+ */
+- (void)setLayerShadow:(UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius;
+
+/**
+ Remove all sublayers.
+ */
+- (void)removeAllSublayers;
+
+@property (nonatomic) CGFloat left;        ///< Shortcut for frame.origin.x.
+@property (nonatomic) CGFloat top;         ///< Shortcut for frame.origin.y
+@property (nonatomic) CGFloat right;       ///< Shortcut for frame.origin.x + frame.size.width
+@property (nonatomic) CGFloat bottom;      ///< Shortcut for frame.origin.y + frame.size.height
+@property (nonatomic) CGFloat width;       ///< Shortcut for frame.size.width.
+@property (nonatomic) CGFloat height;      ///< Shortcut for frame.size.height.
+@property (nonatomic) CGPoint center;      ///< Shortcut for center.
+@property (nonatomic) CGFloat centerX;     ///< Shortcut for center.x
+@property (nonatomic) CGFloat centerY;     ///< Shortcut for center.y
+@property (nonatomic) CGPoint origin;      ///< Shortcut for frame.origin.
+@property (nonatomic, getter=frameSize, setter=setFrameSize:) CGSize  size; ///< Shortcut for frame.size.
+
+
+@property (nonatomic) CGFloat transformRotation;     ///< key path "tranform.rotation"
+@property (nonatomic) CGFloat transformRotationX;    ///< key path "tranform.rotation.x"
+@property (nonatomic) CGFloat transformRotationY;    ///< key path "tranform.rotation.y"
+@property (nonatomic) CGFloat transformRotationZ;    ///< key path "tranform.rotation.z"
+@property (nonatomic) CGFloat transformScale;        ///< key path "tranform.scale"
+@property (nonatomic) CGFloat transformScaleX;       ///< key path "tranform.scale.x"
+@property (nonatomic) CGFloat transformScaleY;       ///< key path "tranform.scale.y"
+@property (nonatomic) CGFloat transformScaleZ;       ///< key path "tranform.scale.z"
+@property (nonatomic) CGFloat transformTranslationX; ///< key path "tranform.translation.x"
+@property (nonatomic) CGFloat transformTranslationY; ///< key path "tranform.translation.y"
+@property (nonatomic) CGFloat transformTranslationZ; ///< key path "tranform.translation.z"
+
+/**
+ Shortcut for transform.m34, -1/1000 is a good value.
+ It should be set before other transform shortcut.
+ */
+@property (nonatomic) CGFloat transformDepth;
+
+/**
+ Wrapper for `contentsGravity` property.
+ */
+@property (nonatomic) UIViewContentMode contentMode;
+
+/**
+ Add a fade animation to layer's contents when the contents is changed.
+ 
+ @param duration Animation duration
+ @param curve    Animation curve.
+ */
+- (void)addFadeAnimationWithDuration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve;
+
+/**
+ Cancel fade animation which is added with "-addFadeAnimationWithDuration:curve:".
+ */
+- (void)removePreviousFadeAnimation;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 324 - 0
YYKit/Base/Quartz/CALayer+YYAdd.m

@@ -0,0 +1,324 @@
+//
+//  CALayer+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/10.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "CALayer+YYAdd.h"
+#import "YYKitMacro.h"
+#import "YYCGUtilities.h"
+
+YYSYNTH_DUMMY_CLASS(CALayer_YYAdd)
+
+
+@implementation CALayer (YYAdd)
+
+- (UIImage *)snapshotImage {
+    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
+    CGContextRef context = UIGraphicsGetCurrentContext();
+    [self renderInContext:context];
+    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return image;
+}
+
+- (NSData *)snapshotPDF {
+    CGRect bounds = self.bounds;
+    NSMutableData *data = [NSMutableData data];
+    CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)data);
+    CGContextRef context = CGPDFContextCreate(consumer, &bounds, NULL);
+    CGDataConsumerRelease(consumer);
+    if (!context) return nil;
+    CGPDFContextBeginPage(context, NULL);
+    CGContextTranslateCTM(context, 0, bounds.size.height);
+    CGContextScaleCTM(context, 1.0, -1.0);
+    [self renderInContext:context];
+    CGPDFContextEndPage(context);
+    CGPDFContextClose(context);
+    CGContextRelease(context);
+    return data;
+}
+
+- (void)setLayerShadow:(UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius {
+    self.shadowColor = color.CGColor;
+    self.shadowOffset = offset;
+    self.shadowRadius = radius;
+    self.shadowOpacity = 1;
+    self.shouldRasterize = YES;
+    self.rasterizationScale = [UIScreen mainScreen].scale;
+}
+
+- (void)removeAllSublayers {
+    while (self.sublayers.count) {
+        [self.sublayers.lastObject removeFromSuperlayer];
+    }
+}
+
+- (CGFloat)left {
+    return self.frame.origin.x;
+}
+
+- (void)setLeft:(CGFloat)x {
+    CGRect frame = self.frame;
+    frame.origin.x = x;
+    self.frame = frame;
+}
+
+- (CGFloat)top {
+    return self.frame.origin.y;
+}
+
+- (void)setTop:(CGFloat)y {
+    CGRect frame = self.frame;
+    frame.origin.y = y;
+    self.frame = frame;
+}
+
+- (CGFloat)right {
+    return self.frame.origin.x + self.frame.size.width;
+}
+
+- (void)setRight:(CGFloat)right {
+    CGRect frame = self.frame;
+    frame.origin.x = right - frame.size.width;
+    self.frame = frame;
+}
+
+- (CGFloat)bottom {
+    return self.frame.origin.y + self.frame.size.height;
+}
+
+- (void)setBottom:(CGFloat)bottom {
+    CGRect frame = self.frame;
+    frame.origin.y = bottom - frame.size.height;
+    self.frame = frame;
+}
+
+- (CGFloat)width {
+    return self.frame.size.width;
+}
+
+- (void)setWidth:(CGFloat)width {
+    CGRect frame = self.frame;
+    frame.size.width = width;
+    self.frame = frame;
+}
+
+- (CGFloat)height {
+    return self.frame.size.height;
+}
+
+- (void)setHeight:(CGFloat)height {
+    CGRect frame = self.frame;
+    frame.size.height = height;
+    self.frame = frame;
+}
+
+- (CGPoint)center {
+    return CGPointMake(self.frame.origin.x + self.frame.size.width * 0.5,
+                       self.frame.origin.y + self.frame.size.height * 0.5);
+}
+
+- (void)setCenter:(CGPoint)center {
+    CGRect frame = self.frame;
+    frame.origin.x = center.x - frame.size.width * 0.5;
+    frame.origin.y = center.y - frame.size.height * 0.5;
+    self.frame = frame;
+}
+
+- (CGFloat)centerX {
+    return self.frame.origin.x + self.frame.size.width * 0.5;
+}
+
+- (void)setCenterX:(CGFloat)centerX {
+    CGRect frame = self.frame;
+    frame.origin.x = centerX - frame.size.width * 0.5;
+    self.frame = frame;
+}
+
+- (CGFloat)centerY {
+    return self.frame.origin.y + self.frame.size.height * 0.5;
+}
+
+- (void)setCenterY:(CGFloat)centerY {
+    CGRect frame = self.frame;
+    frame.origin.y = centerY - frame.size.height * 0.5;
+    self.frame = frame;
+}
+
+- (CGPoint)origin {
+    return self.frame.origin;
+}
+
+- (void)setOrigin:(CGPoint)origin {
+    CGRect frame = self.frame;
+    frame.origin = origin;
+    self.frame = frame;
+}
+
+- (CGSize)frameSize {
+    return self.frame.size;
+}
+
+- (void)setFrameSize:(CGSize)size {
+    CGRect frame = self.frame;
+    frame.size = size;
+    self.frame = frame;
+}
+
+- (CGFloat)transformRotation {
+    NSNumber *v = [self valueForKeyPath:@"transform.rotation"];
+    return v.doubleValue;
+}
+
+- (void)setTransformRotation:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.rotation"];
+}
+
+- (CGFloat)transformRotationX {
+    NSNumber *v = [self valueForKeyPath:@"transform.rotation.x"];
+    return v.doubleValue;
+}
+
+- (void)setTransformRotationX:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.rotation.x"];
+}
+
+- (CGFloat)transformRotationY {
+    NSNumber *v = [self valueForKeyPath:@"transform.rotation.y"];
+    return v.doubleValue;
+}
+
+- (void)setTransformRotationY:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.rotation.y"];
+}
+
+- (CGFloat)transformRotationZ {
+    NSNumber *v = [self valueForKeyPath:@"transform.rotation.z"];
+    return v.doubleValue;
+}
+
+- (void)setTransformRotationZ:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.rotation.z"];
+}
+
+- (CGFloat)transformScaleX {
+    NSNumber *v = [self valueForKeyPath:@"transform.scale.x"];
+    return v.doubleValue;
+}
+
+- (void)setTransformScaleX:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.scale.x"];
+}
+
+- (CGFloat)transformScaleY {
+    NSNumber *v = [self valueForKeyPath:@"transform.scale.y"];
+    return v.doubleValue;
+}
+
+- (void)setTransformScaleY:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.scale.y"];
+}
+
+- (CGFloat)transformScaleZ {
+    NSNumber *v = [self valueForKeyPath:@"transform.scale.z"];
+    return v.doubleValue;
+}
+
+- (void)setTransformScaleZ:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.scale.z"];
+}
+
+- (CGFloat)transformScale {
+    NSNumber *v = [self valueForKeyPath:@"transform.scale"];
+    return v.doubleValue;
+}
+
+- (void)setTransformScale:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.scale"];
+}
+
+- (CGFloat)transformTranslationX {
+    NSNumber *v = [self valueForKeyPath:@"transform.translation.x"];
+    return v.doubleValue;
+}
+
+- (void)setTransformTranslationX:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.translation.x"];
+}
+
+- (CGFloat)transformTranslationY {
+    NSNumber *v = [self valueForKeyPath:@"transform.translation.y"];
+    return v.doubleValue;
+}
+
+- (void)setTransformTranslationY:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.translation.y"];
+}
+
+- (CGFloat)transformTranslationZ {
+    NSNumber *v = [self valueForKeyPath:@"transform.translation.z"];
+    return v.doubleValue;
+}
+
+- (void)setTransformTranslationZ:(CGFloat)v {
+    [self setValue:@(v) forKeyPath:@"transform.translation.z"];
+}
+
+- (CGFloat)transformDepth {
+    return self.transform.m34;
+}
+
+- (void)setTransformDepth:(CGFloat)v {
+    CATransform3D d = self.transform;
+    d.m34 = v;
+    self.transform = d;
+}
+
+- (UIViewContentMode)contentMode {
+    return YYCAGravityToUIViewContentMode(self.contentsGravity);
+}
+
+- (void)setContentMode:(UIViewContentMode)contentMode {
+    self.contentsGravity = YYUIViewContentModeToCAGravity(contentMode);
+}
+
+- (void)addFadeAnimationWithDuration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
+    if (duration <= 0) return;
+    
+    NSString *mediaFunction;
+    switch (curve) {
+        case UIViewAnimationCurveEaseInOut: {
+            mediaFunction = kCAMediaTimingFunctionEaseInEaseOut;
+        } break;
+        case UIViewAnimationCurveEaseIn: {
+            mediaFunction = kCAMediaTimingFunctionEaseIn;
+        } break;
+        case UIViewAnimationCurveEaseOut: {
+            mediaFunction = kCAMediaTimingFunctionEaseOut;
+        } break;
+        case UIViewAnimationCurveLinear: {
+            mediaFunction = kCAMediaTimingFunctionLinear;
+        } break;
+        default: {
+            mediaFunction = kCAMediaTimingFunctionLinear;
+        } break;
+    }
+    
+    CATransition *transition = [CATransition animation];
+    transition.duration = duration;
+    transition.timingFunction = [CAMediaTimingFunction functionWithName:mediaFunction];
+    transition.type = kCATransitionFade;
+    [self addAnimation:transition forKey:@"yykit.fade"];
+}
+
+- (void)removePreviousFadeAnimation {
+    [self removeAnimationForKey:@"yykit.fade"];
+}
+
+@end

+ 338 - 0
YYKit/Base/Quartz/YYCGUtilities.h

@@ -0,0 +1,338 @@
+//
+//  YYCGUtilities.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/28.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+#import <QuartzCore/QuartzCore.h>
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYKitMacro.h>
+#else
+#import "YYKitMacro.h"
+#endif
+
+YY_EXTERN_C_BEGIN
+NS_ASSUME_NONNULL_BEGIN
+
+/// Create an `ARGB` Bitmap context. Returns NULL if an error occurs.
+///
+/// @discussion The function is same as UIGraphicsBeginImageContextWithOptions(),
+/// but it doesn't push the context to UIGraphic, so you can retain the context for reuse.
+CGContextRef _Nullable YYCGContextCreateARGBBitmapContext(CGSize size, BOOL opaque, CGFloat scale);
+
+/// Create a `DeviceGray` Bitmap context. Returns NULL if an error occurs.
+CGContextRef _Nullable YYCGContextCreateGrayBitmapContext(CGSize size, CGFloat scale);
+
+
+
+/// Get main screen's scale.
+CGFloat YYScreenScale();
+
+/// Get main screen's size. Height is always larger than width.
+CGSize YYScreenSize();
+
+
+
+/// Convert degrees to radians.
+static inline CGFloat DegreesToRadians(CGFloat degrees) {
+    return degrees * M_PI / 180;
+}
+
+/// Convert radians to degrees.
+static inline CGFloat RadiansToDegrees(CGFloat radians) {
+    return radians * 180 / M_PI;
+}
+
+
+
+/// Get the transform rotation.
+/// @return the rotation in radians [-PI,PI] ([-180°,180°])
+static inline CGFloat CGAffineTransformGetRotation(CGAffineTransform transform) {
+    return atan2(transform.b, transform.a);
+}
+
+/// Get the transform's scale.x
+static inline CGFloat CGAffineTransformGetScaleX(CGAffineTransform transform) {
+    return  sqrt(transform.a * transform.a + transform.c * transform.c);
+}
+
+/// Get the transform's scale.y
+static inline CGFloat CGAffineTransformGetScaleY(CGAffineTransform transform) {
+    return sqrt(transform.b * transform.b + transform.d * transform.d);
+}
+
+/// Get the transform's translate.x
+static inline CGFloat CGAffineTransformGetTranslateX(CGAffineTransform transform) {
+    return transform.tx;
+}
+
+/// Get the transform's translate.y
+static inline CGFloat CGAffineTransformGetTranslateY(CGAffineTransform transform) {
+    return transform.ty;
+}
+
+/**
+ If you have 3 pair of points transformed by a same CGAffineTransform:
+     p1 (transform->) q1
+     p2 (transform->) q2
+     p3 (transform->) q3
+ This method returns the original transform matrix from these 3 pair of points.
+ 
+ @see http://stackoverflow.com/questions/13291796/calculate-values-for-a-cgaffinetransform-from-three-points-in-each-of-two-uiview
+ */
+CGAffineTransform YYCGAffineTransformGetFromPoints(CGPoint before[3], CGPoint after[3]);
+
+/// Get the transform which can converts a point from the coordinate system of a given view to another.
+CGAffineTransform YYCGAffineTransformGetFromViews(UIView *from, UIView *to);
+
+/// Create a skew transform.
+static inline CGAffineTransform CGAffineTransformMakeSkew(CGFloat x, CGFloat y){
+    CGAffineTransform transform = CGAffineTransformIdentity;
+    transform.c = -x;
+    transform.b = y;
+    return transform;
+}
+
+/// Negates/inverts a UIEdgeInsets.
+static inline UIEdgeInsets UIEdgeInsetsInvert(UIEdgeInsets insets) {
+    return UIEdgeInsetsMake(-insets.top, -insets.left, -insets.bottom, -insets.right);
+}
+
+/// Convert CALayer's gravity string to UIViewContentMode.
+UIViewContentMode YYCAGravityToUIViewContentMode(NSString *gravity);
+
+/// Convert UIViewContentMode to CALayer's gravity string.
+NSString *YYUIViewContentModeToCAGravity(UIViewContentMode contentMode);
+
+
+
+/**
+ Returns a rectangle to fit the @param rect with specified content mode.
+ 
+ @param rect The constrant rect
+ @param size The content size
+ @param mode The content mode
+ @return A rectangle for the given content mode.
+ @discussion UIViewContentModeRedraw is same as UIViewContentModeScaleToFill.
+ */
+CGRect YYCGRectFitWithContentMode(CGRect rect, CGSize size, UIViewContentMode mode);
+
+/// Returns the center for the rectangle.
+static inline CGPoint CGRectGetCenter(CGRect rect) {
+    return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
+}
+
+/// Returns the area of the rectangle.
+static inline CGFloat CGRectGetArea(CGRect rect) {
+    if (CGRectIsNull(rect)) return 0;
+    rect = CGRectStandardize(rect);
+    return rect.size.width * rect.size.height;
+}
+
+/// Returns the distance between two points.
+static inline CGFloat CGPointGetDistanceToPoint(CGPoint p1, CGPoint p2) {
+    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
+}
+
+/// Returns the minmium distance between a point to a rectangle.
+static inline CGFloat CGPointGetDistanceToRect(CGPoint p, CGRect r) {
+    r = CGRectStandardize(r);
+    if (CGRectContainsPoint(r, p)) return 0;
+    CGFloat distV, distH;
+    if (CGRectGetMinY(r) <= p.y && p.y <= CGRectGetMaxY(r)) {
+        distV = 0;
+    } else {
+        distV = p.y < CGRectGetMinY(r) ? CGRectGetMinY(r) - p.y : p.y - CGRectGetMaxY(r);
+    }
+    if (CGRectGetMinX(r) <= p.x && p.x <= CGRectGetMaxX(r)) {
+        distH = 0;
+    } else {
+        distH = p.x < CGRectGetMinX(r) ? CGRectGetMinX(r) - p.x : p.x - CGRectGetMaxX(r);
+    }
+    return MAX(distV, distH);
+}
+
+
+
+/// Convert point to pixel.
+static inline CGFloat CGFloatToPixel(CGFloat value) {
+    return value * YYScreenScale();
+}
+
+/// Convert pixel to point.
+static inline CGFloat CGFloatFromPixel(CGFloat value) {
+    return value / YYScreenScale();
+}
+
+
+
+/// floor point value for pixel-aligned
+static inline CGFloat CGFloatPixelFloor(CGFloat value) {
+    CGFloat scale = YYScreenScale();
+    return floor(value * scale) / scale;
+}
+
+/// round point value for pixel-aligned
+static inline CGFloat CGFloatPixelRound(CGFloat value) {
+    CGFloat scale = YYScreenScale();
+    return round(value * scale) / scale;
+}
+
+/// ceil point value for pixel-aligned
+static inline CGFloat CGFloatPixelCeil(CGFloat value) {
+    CGFloat scale = YYScreenScale();
+    return ceil(value * scale) / scale;
+}
+
+/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
+static inline CGFloat CGFloatPixelHalf(CGFloat value) {
+    CGFloat scale = YYScreenScale();
+    return (floor(value * scale) + 0.5) / scale;
+}
+
+
+
+/// floor point value for pixel-aligned
+static inline CGPoint CGPointPixelFloor(CGPoint point) {
+    CGFloat scale = YYScreenScale();
+    return CGPointMake(floor(point.x * scale) / scale,
+                       floor(point.y * scale) / scale);
+}
+
+/// round point value for pixel-aligned
+static inline CGPoint CGPointPixelRound(CGPoint point) {
+    CGFloat scale = YYScreenScale();
+    return CGPointMake(round(point.x * scale) / scale,
+                       round(point.y * scale) / scale);
+}
+
+/// ceil point value for pixel-aligned
+static inline CGPoint CGPointPixelCeil(CGPoint point) {
+    CGFloat scale = YYScreenScale();
+    return CGPointMake(ceil(point.x * scale) / scale,
+                       ceil(point.y * scale) / scale);
+}
+
+/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
+static inline CGPoint CGPointPixelHalf(CGPoint point) {
+    CGFloat scale = YYScreenScale();
+    return CGPointMake((floor(point.x * scale) + 0.5) / scale,
+                       (floor(point.y * scale) + 0.5) / scale);
+}
+
+
+
+/// floor point value for pixel-aligned
+static inline CGSize CGSizePixelFloor(CGSize size) {
+    CGFloat scale = YYScreenScale();
+    return CGSizeMake(floor(size.width * scale) / scale,
+                      floor(size.height * scale) / scale);
+}
+
+/// round point value for pixel-aligned
+static inline CGSize CGSizePixelRound(CGSize size) {
+    CGFloat scale = YYScreenScale();
+    return CGSizeMake(round(size.width * scale) / scale,
+                      round(size.height * scale) / scale);
+}
+
+/// ceil point value for pixel-aligned
+static inline CGSize CGSizePixelCeil(CGSize size) {
+    CGFloat scale = YYScreenScale();
+    return CGSizeMake(ceil(size.width * scale) / scale,
+                      ceil(size.height * scale) / scale);
+}
+
+/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
+static inline CGSize CGSizePixelHalf(CGSize size) {
+    CGFloat scale = YYScreenScale();
+    return CGSizeMake((floor(size.width * scale) + 0.5) / scale,
+                       (floor(size.height * scale) + 0.5) / scale);
+}
+
+
+
+/// floor point value for pixel-aligned
+static inline CGRect CGRectPixelFloor(CGRect rect) {
+    CGPoint origin = CGPointPixelCeil(rect.origin);
+    CGPoint corner = CGPointPixelFloor(CGPointMake(rect.origin.x + rect.size.width,
+                                                   rect.origin.y + rect.size.height));
+    CGRect ret = CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
+    if (ret.size.width < 0) ret.size.width = 0;
+    if (ret.size.height < 0) ret.size.height = 0;
+    return ret;
+}
+
+/// round point value for pixel-aligned
+static inline CGRect CGRectPixelRound(CGRect rect) {
+    CGPoint origin = CGPointPixelRound(rect.origin);
+    CGPoint corner = CGPointPixelRound(CGPointMake(rect.origin.x + rect.size.width,
+                                                  rect.origin.y + rect.size.height));
+    return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
+}
+
+/// ceil point value for pixel-aligned
+static inline CGRect CGRectPixelCeil(CGRect rect) {
+    CGPoint origin = CGPointPixelFloor(rect.origin);
+    CGPoint corner = CGPointPixelCeil(CGPointMake(rect.origin.x + rect.size.width,
+                                                   rect.origin.y + rect.size.height));
+    return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
+}
+
+/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
+static inline CGRect CGRectPixelHalf(CGRect rect) {
+    CGPoint origin = CGPointPixelHalf(rect.origin);
+    CGPoint corner = CGPointPixelHalf(CGPointMake(rect.origin.x + rect.size.width,
+                                                  rect.origin.y + rect.size.height));
+    return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
+}
+
+
+
+/// floor UIEdgeInset for pixel-aligned
+static inline UIEdgeInsets UIEdgeInsetPixelFloor(UIEdgeInsets insets) {
+    insets.top = CGFloatPixelFloor(insets.top);
+    insets.left = CGFloatPixelFloor(insets.left);
+    insets.bottom = CGFloatPixelFloor(insets.bottom);
+    insets.right = CGFloatPixelFloor(insets.right);
+    return insets;
+}
+
+/// ceil UIEdgeInset for pixel-aligned
+static inline UIEdgeInsets UIEdgeInsetPixelCeil(UIEdgeInsets insets) {
+    insets.top = CGFloatPixelCeil(insets.top);
+    insets.left = CGFloatPixelCeil(insets.left);
+    insets.bottom = CGFloatPixelCeil(insets.bottom);
+    insets.right = CGFloatPixelCeil(insets.right);
+    return insets;
+}
+
+// main screen's scale
+#ifndef kScreenScale
+#define kScreenScale YYScreenScale()
+#endif
+
+// main screen's size (portrait)
+#ifndef kScreenSize
+#define kScreenSize YYScreenSize()
+#endif
+
+// main screen's width (portrait)
+#ifndef kScreenWidth
+#define kScreenWidth YYScreenSize().width
+#endif
+
+// main screen's height (portrait)
+#ifndef kScreenHeight
+#define kScreenHeight YYScreenSize().height
+#endif
+
+NS_ASSUME_NONNULL_END
+YY_EXTERN_C_END

+ 271 - 0
YYKit/Base/Quartz/YYCGUtilities.m

@@ -0,0 +1,271 @@
+//
+//  YYCGUtilities.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/28.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYCGUtilities.h"
+#import <Accelerate/Accelerate.h>
+#import "UIView+YYAdd.h"
+
+CGContextRef YYCGContextCreateARGBBitmapContext(CGSize size, BOOL opaque, CGFloat scale) {
+    size_t width = ceil(size.width * scale);
+    size_t height = ceil(size.height * scale);
+    if (width < 1 || height < 1) return NULL;
+    
+    //pre-multiplied ARGB, 8-bits per component
+    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
+    CGImageAlphaInfo alphaInfo = (opaque ? kCGImageAlphaNoneSkipFirst : kCGImageAlphaPremultipliedFirst);
+    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGBitmapByteOrderDefault | alphaInfo);
+    CGColorSpaceRelease(space);
+    if (context) {
+        CGContextTranslateCTM(context, 0, height);
+        CGContextScaleCTM(context, scale, -scale);
+    }
+    return context;
+}
+
+CGContextRef YYCGContextCreateGrayBitmapContext(CGSize size, CGFloat scale) {
+    size_t width = ceil(size.width * scale);
+    size_t height = ceil(size.height * scale);
+    if (width < 1 || height < 1) return NULL;
+    
+    //DeviceGray, 8-bits per component
+    CGColorSpaceRef space = CGColorSpaceCreateDeviceGray();
+    CGImageAlphaInfo alphaInfo = kCGImageAlphaNone;
+    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGBitmapByteOrderDefault | alphaInfo);
+    CGColorSpaceRelease(space);
+    if (context) {
+        CGContextTranslateCTM(context, 0, height);
+        CGContextScaleCTM(context, scale, -scale);
+    }
+    return context;
+}
+
+CGFloat YYScreenScale() {
+    static CGFloat scale;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        scale = [UIScreen mainScreen].scale;
+    });
+    return scale;
+}
+
+CGSize YYScreenSize() {
+    static CGSize size;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        size = [UIScreen mainScreen].bounds.size;
+        if (size.height < size.width) {
+            CGFloat tmp = size.height;
+            size.height = size.width;
+            size.width = tmp;
+        }
+    });
+    return size;
+}
+
+// return 0 when succeed
+static int matrix_invert(__CLPK_integer N, double *matrix) {
+    __CLPK_integer error = 0;
+    __CLPK_integer pivot_tmp[6 * 6];
+    __CLPK_integer *pivot = pivot_tmp;
+    double workspace_tmp[6 * 6];
+    double *workspace = workspace_tmp;
+    bool need_free = false;
+    
+    if (N > 6) {
+        need_free = true;
+        pivot = malloc(N * N * sizeof(__CLPK_integer));
+        if (!pivot) return -1;
+        workspace = malloc(N * sizeof(double));
+        if (!workspace) {
+            free(pivot);
+            return -1;
+        }
+    }
+    
+    dgetrf_(&N, &N, matrix, &N, pivot, &error);
+    
+    if (error == 0) {
+        dgetri_(&N, matrix, &N, pivot, workspace, &N, &error);
+    }
+    
+    if (need_free) {
+        free(pivot);
+        free(workspace);
+    }
+    return error;
+}
+
+CGAffineTransform YYCGAffineTransformGetFromPoints(CGPoint before[3], CGPoint after[3]) {
+    if (before == NULL || after == NULL) return CGAffineTransformIdentity;
+    
+    CGPoint p1, p2, p3, q1, q2, q3;
+    p1 = before[0]; p2 = before[1]; p3 = before[2];
+    q1 =  after[0]; q2 =  after[1]; q3 =  after[2];
+    
+    double A[36];
+    A[ 0] = p1.x; A[ 1] = p1.y; A[ 2] = 0; A[ 3] = 0; A[ 4] = 1; A[ 5] = 0;
+    A[ 6] = 0; A[ 7] = 0; A[ 8] = p1.x; A[ 9] = p1.y; A[10] = 0; A[11] = 1;
+    A[12] = p2.x; A[13] = p2.y; A[14] = 0; A[15] = 0; A[16] = 1; A[17] = 0;
+    A[18] = 0; A[19] = 0; A[20] = p2.x; A[21] = p2.y; A[22] = 0; A[23] = 1;
+    A[24] = p3.x; A[25] = p3.y; A[26] = 0; A[27] = 0; A[28] = 1; A[29] = 0;
+    A[30] = 0; A[31] = 0; A[32] = p3.x; A[33] = p3.y; A[34] = 0; A[35] = 1;
+    
+    int error = matrix_invert(6, A);
+    if (error) return CGAffineTransformIdentity;
+    
+    double B[6];
+    B[0] = q1.x; B[1] = q1.y; B[2] = q2.x; B[3] = q2.y; B[4] = q3.x; B[5] = q3.y;
+    
+    double M[6];
+    M[0] = A[ 0] * B[0] + A[ 1] * B[1] + A[ 2] * B[2] + A[ 3] * B[3] + A[ 4] * B[4] + A[ 5] * B[5];
+    M[1] = A[ 6] * B[0] + A[ 7] * B[1] + A[ 8] * B[2] + A[ 9] * B[3] + A[10] * B[4] + A[11] * B[5];
+    M[2] = A[12] * B[0] + A[13] * B[1] + A[14] * B[2] + A[15] * B[3] + A[16] * B[4] + A[17] * B[5];
+    M[3] = A[18] * B[0] + A[19] * B[1] + A[20] * B[2] + A[21] * B[3] + A[22] * B[4] + A[23] * B[5];
+    M[4] = A[24] * B[0] + A[25] * B[1] + A[26] * B[2] + A[27] * B[3] + A[28] * B[4] + A[29] * B[5];
+    M[5] = A[30] * B[0] + A[31] * B[1] + A[32] * B[2] + A[33] * B[3] + A[34] * B[4] + A[35] * B[5];
+    
+    CGAffineTransform transform = CGAffineTransformMake(M[0], M[2], M[1], M[3], M[4], M[5]);
+    return transform;
+}
+
+CGAffineTransform YYCGAffineTransformGetFromViews(UIView *from, UIView *to) {
+    if (!from || !to) return CGAffineTransformIdentity;
+    
+    CGPoint before[3], after[3];
+    before[0] = CGPointMake(0, 0);
+    before[1] = CGPointMake(0, 1);
+    before[2] = CGPointMake(1, 0);
+    after[0] = [from convertPoint:before[0] toViewOrWindow:to];
+    after[1] = [from convertPoint:before[1] toViewOrWindow:to];
+    after[2] = [from convertPoint:before[2] toViewOrWindow:to];
+    
+    return YYCGAffineTransformGetFromPoints(before, after);
+}
+
+UIViewContentMode YYCAGravityToUIViewContentMode(NSString *gravity) {
+    static NSDictionary *dic;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        dic = @{ kCAGravityCenter:@(UIViewContentModeCenter),
+                 kCAGravityTop:@(UIViewContentModeTop),
+                 kCAGravityBottom:@(UIViewContentModeBottom),
+                 kCAGravityLeft:@(UIViewContentModeLeft),
+                 kCAGravityRight:@(UIViewContentModeRight),
+                 kCAGravityTopLeft:@(UIViewContentModeTopLeft),
+                 kCAGravityTopRight:@(UIViewContentModeTopRight),
+                 kCAGravityBottomLeft:@(UIViewContentModeBottomLeft),
+                 kCAGravityBottomRight:@(UIViewContentModeBottomRight),
+                 kCAGravityResize:@(UIViewContentModeScaleToFill),
+                 kCAGravityResizeAspect:@(UIViewContentModeScaleAspectFit),
+                 kCAGravityResizeAspectFill:@(UIViewContentModeScaleAspectFill) };
+    });
+    if (!gravity) return UIViewContentModeScaleToFill;
+    return (UIViewContentMode)((NSNumber *)dic[gravity]).integerValue;
+}
+
+NSString *YYUIViewContentModeToCAGravity(UIViewContentMode contentMode) {
+    switch (contentMode) {
+        case UIViewContentModeScaleToFill: return kCAGravityResize;
+        case UIViewContentModeScaleAspectFit: return kCAGravityResizeAspect;
+        case UIViewContentModeScaleAspectFill: return kCAGravityResizeAspectFill;
+        case UIViewContentModeRedraw: return kCAGravityResize;
+        case UIViewContentModeCenter: return kCAGravityCenter;
+        case UIViewContentModeTop: return kCAGravityTop;
+        case UIViewContentModeBottom: return kCAGravityBottom;
+        case UIViewContentModeLeft: return kCAGravityLeft;
+        case UIViewContentModeRight: return kCAGravityRight;
+        case UIViewContentModeTopLeft: return kCAGravityTopLeft;
+        case UIViewContentModeTopRight: return kCAGravityTopRight;
+        case UIViewContentModeBottomLeft: return kCAGravityBottomLeft;
+        case UIViewContentModeBottomRight: return kCAGravityBottomRight;
+        default: return kCAGravityResize;
+    }
+}
+
+CGRect YYCGRectFitWithContentMode(CGRect rect, CGSize size, UIViewContentMode mode) {
+    rect = CGRectStandardize(rect);
+    size.width = size.width < 0 ? -size.width : size.width;
+    size.height = size.height < 0 ? -size.height : size.height;
+    CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
+    switch (mode) {
+        case UIViewContentModeScaleAspectFit:
+        case UIViewContentModeScaleAspectFill: {
+            if (rect.size.width < 0.01 || rect.size.height < 0.01 ||
+                size.width < 0.01 || size.height < 0.01) {
+                rect.origin = center;
+                rect.size = CGSizeZero;
+            } else {
+                CGFloat scale;
+                if (mode == UIViewContentModeScaleAspectFit) {
+                    if (size.width / size.height < rect.size.width / rect.size.height) {
+                        scale = rect.size.height / size.height;
+                    } else {
+                        scale = rect.size.width / size.width;
+                    }
+                } else {
+                    if (size.width / size.height < rect.size.width / rect.size.height) {
+                        scale = rect.size.width / size.width;
+                    } else {
+                        scale = rect.size.height / size.height;
+                    }
+                }
+                size.width *= scale;
+                size.height *= scale;
+                rect.size = size;
+                rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5);
+            }
+        } break;
+        case UIViewContentModeCenter: {
+            rect.size = size;
+            rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5);
+        } break;
+        case UIViewContentModeTop: {
+            rect.origin.x = center.x - size.width * 0.5;
+            rect.size = size;
+        } break;
+        case UIViewContentModeBottom: {
+            rect.origin.x = center.x - size.width * 0.5;
+            rect.origin.y += rect.size.height - size.height;
+            rect.size = size;
+        } break;
+        case UIViewContentModeLeft: {
+            rect.origin.y = center.y - size.height * 0.5;
+            rect.size = size;
+        } break;
+        case UIViewContentModeRight: {
+            rect.origin.y = center.y - size.height * 0.5;
+            rect.origin.x += rect.size.width - size.width;
+            rect.size = size;
+        } break;
+        case UIViewContentModeTopLeft: {
+            rect.size = size;
+        } break;
+        case UIViewContentModeTopRight: {
+            rect.origin.x += rect.size.width - size.width;
+            rect.size = size;
+        } break;
+        case UIViewContentModeBottomLeft: {
+            rect.origin.y += rect.size.height - size.height;
+            rect.size = size;
+        } break;
+        case UIViewContentModeBottomRight: {
+            rect.origin.x += rect.size.width - size.width;
+            rect.origin.y += rect.size.height - size.height;
+            rect.size = size;
+        } break;
+        case UIViewContentModeScaleToFill:
+        case UIViewContentModeRedraw:
+        default: {
+            rect = rect;
+        }
+    }
+    return rect;
+}

+ 89 - 0
YYKit/Base/UIKit/UIApplication+YYAdd.h

@@ -0,0 +1,89 @@
+//
+//  UIApplication+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIApplication`.
+ */
+@interface UIApplication (YYAdd)
+
+/// "Documents" folder in this app's sandbox.
+@property (nonatomic, readonly) NSURL *documentsURL;
+@property (nonatomic, readonly) NSString *documentsPath;
+
+/// "Caches" folder in this app's sandbox.
+@property (nonatomic, readonly) NSURL *cachesURL;
+@property (nonatomic, readonly) NSString *cachesPath;
+
+/// "Library" folder in this app's sandbox.
+@property (nonatomic, readonly) NSURL *libraryURL;
+@property (nonatomic, readonly) NSString *libraryPath;
+
+/// Application's Bundle Name (show in SpringBoard).
+@property (nullable, nonatomic, readonly) NSString *appBundleName;
+
+/// Application's Bundle ID.  e.g. "com.ibireme.MyApp"
+@property (nullable, nonatomic, readonly) NSString *appBundleID;
+
+/// Application's Version.  e.g. "1.2.0"
+@property (nullable, nonatomic, readonly) NSString *appVersion;
+
+/// Application's Build number. e.g. "123"
+@property (nullable, nonatomic, readonly) NSString *appBuildVersion;
+
+/// Whether this app is pirated (not install from appstore).
+@property (nonatomic, readonly) BOOL isPirated;
+
+/// Whether this app is being debugged (debugger attached).
+@property (nonatomic, readonly) BOOL isBeingDebugged;
+
+/// Current thread real memory used in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryUsage;
+
+/// Current thread CPU usage, 1.0 means 100%. (-1 when error occurs)
+@property (nonatomic, readonly) float cpuUsage;
+
+
+/**
+ Increments the number of active network requests.
+ If this number was zero before incrementing, this will start animating the 
+ status bar network activity indicator.
+ 
+ This method is thread safe.
+ 
+ This method has no effect in App Extension.
+ */
+- (void)incrementNetworkActivityCount;
+
+/**
+ Decrements the number of active network requests. 
+ If this number becomes zero after decrementing, this will stop animating the 
+ status bar network activity indicator.
+ 
+ This method is thread safe.
+ 
+ This method has no effect in App Extension.
+ */
+- (void)decrementNetworkActivityCount;
+
+
+/// Returns YES in App Extension.
++ (BOOL)isAppExtension;
+
+/// Same as sharedApplication, but returns nil in App Extension.
++ (nullable UIApplication *)sharedExtensionApplication;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 239 - 0
YYKit/Base/UIKit/UIApplication+YYAdd.m

@@ -0,0 +1,239 @@
+//
+//  UIApplication+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIApplication+YYAdd.h"
+#import "NSArray+YYAdd.h"
+#import "NSObject+YYAdd.h"
+#import "YYKitMacro.h"
+#import "UIDevice+YYAdd.h"
+#import <sys/sysctl.h>
+#import <mach/mach.h>
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(UIApplication_YYAdd)
+
+#define kNetworkIndicatorDelay (1/30.0)
+@interface _YYUIApplicationNetworkIndicatorInfo : NSObject
+@property (nonatomic, assign) NSInteger count;
+@property (nonatomic, strong) NSTimer *timer;
+@end
+
+@implementation _YYUIApplicationNetworkIndicatorInfo
+@end
+
+
+@implementation UIApplication (YYAdd)
+
+- (NSURL *)documentsURL {
+    return [[[NSFileManager defaultManager]
+             URLsForDirectory:NSDocumentDirectory
+             inDomains:NSUserDomainMask] lastObject];
+}
+
+- (NSString *)documentsPath {
+    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
+}
+
+- (NSURL *)cachesURL {
+    return [[[NSFileManager defaultManager]
+             URLsForDirectory:NSCachesDirectory
+             inDomains:NSUserDomainMask] lastObject];
+}
+
+- (NSString *)cachesPath {
+    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
+}
+
+- (NSURL *)libraryURL {
+    return [[[NSFileManager defaultManager]
+             URLsForDirectory:NSLibraryDirectory
+             inDomains:NSUserDomainMask] lastObject];
+}
+
+- (NSString *)libraryPath {
+    return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
+}
+
+- (BOOL)isPirated {
+    if ([[UIDevice currentDevice] isSimulator]) return YES; // Simulator is not from appstore
+    
+    if (getgid() <= 10) return YES; // process ID shouldn't be root
+    
+    if ([[[NSBundle mainBundle] infoDictionary] objectForKey:@"SignerIdentity"]) {
+        return YES;
+    }
+    
+    if (![self _yy_fileExistInMainBundle:@"_CodeSignature"]) {
+        return YES;
+    }
+    
+    if (![self _yy_fileExistInMainBundle:@"SC_Info"]) {
+        return YES;
+    }
+    
+    //if someone really want to crack your app, this method is useless..
+    //you may change this method's name, encrypt the code and do more check..
+    return NO;
+}
+
+- (BOOL)_yy_fileExistInMainBundle:(NSString *)name {
+    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
+    NSString *path = [NSString stringWithFormat:@"%@/%@", bundlePath, name];
+    return [[NSFileManager defaultManager] fileExistsAtPath:path];
+}
+
+- (NSString *)appBundleName {
+    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
+}
+
+- (NSString *)appBundleID {
+    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
+}
+
+- (NSString *)appVersion {
+    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
+}
+
+- (NSString *)appBuildVersion {
+    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
+}
+
+- (BOOL)isBeingDebugged {
+    size_t size = sizeof(struct kinfo_proc);
+    struct kinfo_proc info;
+    int ret = 0, name[4];
+    memset(&info, 0, sizeof(struct kinfo_proc));
+    
+    name[0] = CTL_KERN;
+    name[1] = KERN_PROC;
+    name[2] = KERN_PROC_PID; name[3] = getpid();
+    
+    if (ret == (sysctl(name, 4, &info, &size, NULL, 0))) {
+        return ret != 0;
+    }
+    return (info.kp_proc.p_flag & P_TRACED) ? YES : NO;
+}
+
+- (int64_t)memoryUsage {
+    struct task_basic_info info;
+    mach_msg_type_number_t size = sizeof(info);
+    kern_return_t kern = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);
+    if (kern != KERN_SUCCESS) return -1;
+    return info.resident_size;
+}
+
+- (float)cpuUsage {
+    kern_return_t kr;
+    task_info_data_t tinfo;
+    mach_msg_type_number_t task_info_count;
+    
+    task_info_count = TASK_INFO_MAX;
+    kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
+    if (kr != KERN_SUCCESS) {
+        return -1;
+    }
+    
+    thread_array_t thread_list;
+    mach_msg_type_number_t thread_count;
+    
+    thread_info_data_t thinfo;
+    mach_msg_type_number_t thread_info_count;
+    
+    thread_basic_info_t basic_info_th;
+    
+    kr = task_threads(mach_task_self(), &thread_list, &thread_count);
+    if (kr != KERN_SUCCESS) {
+        return -1;
+    }
+    
+    long tot_sec = 0;
+    long tot_usec = 0;
+    float tot_cpu = 0;
+    int j;
+    
+    for (j = 0; j < thread_count; j++) {
+        thread_info_count = THREAD_INFO_MAX;
+        kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
+                         (thread_info_t)thinfo, &thread_info_count);
+        if (kr != KERN_SUCCESS) {
+            return -1;
+        }
+        
+        basic_info_th = (thread_basic_info_t)thinfo;
+        
+        if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
+            tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
+            tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
+            tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE;
+        }
+    }
+    
+    kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
+    assert(kr == KERN_SUCCESS);
+    
+    return tot_cpu;
+}
+
+YYSYNTH_DYNAMIC_PROPERTY_OBJECT(networkActivityInfo, setNetworkActivityInfo, RETAIN_NONATOMIC, _YYUIApplicationNetworkIndicatorInfo *);
+
+- (void)_delaySetActivity:(NSTimer *)timer {
+    NSNumber *visiable = timer.userInfo;
+    if (self.networkActivityIndicatorVisible != visiable.boolValue) {
+        [self setNetworkActivityIndicatorVisible:visiable.boolValue];
+    }
+    [timer invalidate];
+}
+
+- (void)_changeNetworkActivityCount:(NSInteger)delta {
+    @synchronized(self){
+        dispatch_async_on_main_queue(^{
+            _YYUIApplicationNetworkIndicatorInfo *info = [self networkActivityInfo];
+            if (!info) {
+                info = [_YYUIApplicationNetworkIndicatorInfo new];
+                [self setNetworkActivityInfo:info];
+            }
+            NSInteger count = info.count;
+            count += delta;
+            info.count = count;
+            [info.timer invalidate];
+            info.timer = [NSTimer timerWithTimeInterval:kNetworkIndicatorDelay target:self selector:@selector(_delaySetActivity:) userInfo:@(info.count > 0) repeats:NO];
+            [[NSRunLoop mainRunLoop] addTimer:info.timer forMode:NSRunLoopCommonModes];
+        });
+    }
+}
+
+- (void)incrementNetworkActivityCount {
+    [self _changeNetworkActivityCount:1];
+}
+
+- (void)decrementNetworkActivityCount {
+    [self _changeNetworkActivityCount:-1];
+}
+
++ (BOOL)isAppExtension {
+    static BOOL isAppExtension = NO;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        Class cls = NSClassFromString(@"UIApplication");
+        if(!cls || ![cls respondsToSelector:@selector(sharedApplication)]) isAppExtension = YES;
+        if ([[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"]) isAppExtension = YES;
+    });
+    return isAppExtension;
+}
+
++ (UIApplication *)sharedExtensionApplication {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wundeclared-selector"
+    return [self isAppExtension] ? nil : [UIApplication performSelector:@selector(sharedApplication)];
+#pragma clang diagnostic pop
+}
+
+@end

+ 32 - 0
YYKit/Base/UIKit/UIBarButtonItem+YYAdd.h

@@ -0,0 +1,32 @@
+//
+//  UIBarButtonItem+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/10/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIBarButtonItem`.
+ */
+@interface UIBarButtonItem (YYAdd)
+
+/**
+ The block that invoked when the item is selected. The objects captured by block
+ will retained by the ButtonItem.
+ 
+ @discussion This param is conflict with `target` and `action` property.
+ Set this will set `target` and `action` property to some internal objects.
+ */
+@property (nullable, nonatomic, copy) void (^actionBlock)(id);
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 62 - 0
YYKit/Base/UIKit/UIBarButtonItem+YYAdd.m

@@ -0,0 +1,62 @@
+//
+//  UIBarButtonItem+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/10/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIBarButtonItem+YYAdd.h"
+#import "YYKitMacro.h"
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(UIBarButtonItem_YYAdd)
+
+
+static const int block_key;
+
+@interface _YYUIBarButtonItemBlockTarget : NSObject
+
+@property (nonatomic, copy) void (^block)(id sender);
+
+- (id)initWithBlock:(void (^)(id sender))block;
+- (void)invoke:(id)sender;
+
+@end
+
+@implementation _YYUIBarButtonItemBlockTarget
+
+- (id)initWithBlock:(void (^)(id sender))block{
+    self = [super init];
+    if (self) {
+        _block = [block copy];
+    }
+    return self;
+}
+
+- (void)invoke:(id)sender {
+    if (self.block) self.block(sender);
+}
+
+@end
+
+
+@implementation UIBarButtonItem (YYAdd)
+
+- (void)setActionBlock:(void (^)(id sender))block {
+    _YYUIBarButtonItemBlockTarget *target = [[_YYUIBarButtonItemBlockTarget alloc] initWithBlock:block];
+    objc_setAssociatedObject(self, &block_key, target, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    
+    [self setTarget:target];
+    [self setAction:@selector(invoke:)];
+}
+
+- (void (^)(id)) actionBlock {
+    _YYUIBarButtonItemBlockTarget *target = objc_getAssociatedObject(self, &block_key);
+    return target.block;
+}
+
+@end

+ 37 - 0
YYKit/Base/UIKit/UIBezierPath+YYAdd.h

@@ -0,0 +1,37 @@
+//
+//  UIBezierPath+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/30.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIBezierPath`.
+ */
+@interface UIBezierPath (YYAdd)
+
+/**
+ Creates and returns a new UIBezierPath object initialized with the text glyphs
+ generated from the specified font.
+ 
+ @discussion It doesnot support apple emoji. If you want get emoji image, try
+ [UIImage imageWithEmoji:size:] in `UIImage(YYAdd)`.
+ 
+ @param text The text to generate glyph path.
+ @param font The font to generate glyph path.
+ 
+ @return A new path object with the text and font, or nil if an error occurs.
+ */
++ (nullable UIBezierPath *)bezierPathWithText:(NSString *)text font:(UIFont *)font;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 64 - 0
YYKit/Base/UIKit/UIBezierPath+YYAdd.m

@@ -0,0 +1,64 @@
+//
+//  UIBezierPath+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/30.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIBezierPath+YYAdd.h"
+#import "UIFont+YYAdd.h"
+#import <CoreText/CoreText.h>
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(UIBezierPath_YYAdd)
+
+
+@implementation UIBezierPath (YYAdd)
+
++ (UIBezierPath *)bezierPathWithText:(NSString *)text font:(UIFont *)font {
+    CTFontRef ctFont = font.CTFontRef;
+    if (!ctFont) return nil;
+    NSDictionary *attrs = @{ (__bridge id)kCTFontAttributeName:(__bridge id)ctFont };
+    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:text attributes:attrs];
+    CFRelease(ctFont);
+    
+    CTLineRef line = CTLineCreateWithAttributedString((__bridge CFTypeRef)attrString);
+    if (!line) return nil;
+    
+    CGMutablePathRef cgPath = CGPathCreateMutable();
+    CFArrayRef runs = CTLineGetGlyphRuns(line);
+    for (CFIndex iRun = 0, iRunMax = CFArrayGetCount(runs); iRun < iRunMax; iRun++) {
+        CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, iRun);
+        CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
+        
+        for (CFIndex iGlyph = 0, iGlyphMax = CTRunGetGlyphCount(run); iGlyph < iGlyphMax; iGlyph++) {
+            CFRange glyphRange = CFRangeMake(iGlyph, 1);
+            CGGlyph glyph;
+            CGPoint position;
+            CTRunGetGlyphs(run, glyphRange, &glyph);
+            CTRunGetPositions(run, glyphRange, &position);
+            
+            CGPathRef glyphPath = CTFontCreatePathForGlyph(runFont, glyph, NULL);
+            if (glyphPath) {
+                CGAffineTransform transform = CGAffineTransformMakeTranslation(position.x, position.y);
+                CGPathAddPath(cgPath, &transform, glyphPath);
+                CGPathRelease(glyphPath);
+            }
+        }
+    }
+    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:cgPath];
+    CGRect boundingBox = CGPathGetPathBoundingBox(cgPath);
+    CFRelease(cgPath);
+    CFRelease(line);
+    
+    [path applyTransform:CGAffineTransformMakeScale(1.0, -1.0)];
+    [path applyTransform:CGAffineTransformMakeTranslation(0.0, boundingBox.size.height)];
+    
+    return path;
+}
+
+@end

+ 358 - 0
YYKit/Base/UIKit/UIColor+YYAdd.h

@@ -0,0 +1,358 @@
+//
+//  UIColor+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+extern void YY_RGB2HSL(CGFloat r, CGFloat g, CGFloat b,
+                       CGFloat *h, CGFloat *s, CGFloat *l);
+
+extern void YY_HSL2RGB(CGFloat h, CGFloat s, CGFloat l,
+                       CGFloat *r, CGFloat *g, CGFloat *b);
+
+extern void YY_RGB2HSB(CGFloat r, CGFloat g, CGFloat b,
+                       CGFloat *h, CGFloat *s, CGFloat *v);
+
+extern void YY_HSB2RGB(CGFloat h, CGFloat s, CGFloat v,
+                       CGFloat *r, CGFloat *g, CGFloat *b);
+
+extern void YY_RGB2CMYK(CGFloat r, CGFloat g, CGFloat b,
+                        CGFloat *c, CGFloat *m, CGFloat *y, CGFloat *k);
+
+extern void YY_CMYK2RGB(CGFloat c, CGFloat m, CGFloat y, CGFloat k,
+                        CGFloat *r, CGFloat *g, CGFloat *b);
+
+extern void YY_HSB2HSL(CGFloat h, CGFloat s, CGFloat b,
+                       CGFloat *hh, CGFloat *ss, CGFloat *ll);
+
+extern void YY_HSL2HSB(CGFloat h, CGFloat s, CGFloat l,
+                       CGFloat *hh, CGFloat *ss, CGFloat *bb);
+
+
+/*
+ Create UIColor with a hex string.
+ Example: UIColorHex(0xF0F), UIColorHex(66ccff), UIColorHex(#66CCFF88)
+ 
+ Valid format: #RGB #RGBA #RRGGBB #RRGGBBAA 0xRGB ...
+ The `#` or "0x" sign is not required.
+ */
+#ifndef UIColorHex
+#define UIColorHex(_hex_)   [UIColor colorWithHexString:((__bridge NSString *)CFSTR(#_hex_))]
+#endif
+
+/**
+ Provide some method for `UIColor` to convert color between
+ RGB,HSB,HSL,CMYK and Hex.
+
+ | Color space | Meaning                                |
+ |-------------|----------------------------------------|
+ | RGB *       | Red, Green, Blue                       |
+ | HSB(HSV) *  | Hue, Saturation, Brightness (Value)    |
+ | HSL         | Hue, Saturation, Lightness             |
+ | CMYK        | Cyan, Magenta, Yellow, Black           |
+ 
+ Apple use RGB & HSB default.
+ 
+ All the value in this category is float number in the range `0.0` to `1.0`.
+ Values below `0.0` are interpreted as `0.0`,
+ and values above `1.0` are interpreted as `1.0`.
+ 
+ If you want convert color between more color space (CIEXYZ,Lab,YUV...),
+ see https://github.com/ibireme/yy_color_convertor
+ */
+@interface UIColor (YYAdd)
+
+
+#pragma mark - Create a UIColor Object
+///=============================================================================
+/// @name Creating a UIColor Object
+///=============================================================================
+
+/**
+ Creates and returns a color object using the specified opacity
+ and HSL color space component values.
+
+ @param hue        The hue component of the color object in the HSL color space,
+                   specified as a value from 0.0 to 1.0.
+
+ @param saturation The saturation component of the color object in the HSL color space,
+                   specified as a value from 0.0 to 1.0.
+ 
+ @param lightness  The lightness component of the color object in the HSL color space,
+                   specified as a value from 0.0 to 1.0.
+ 
+ @param alpha      The opacity value of the color object, 
+                   specified as a value from 0.0 to 1.0.
+ 
+ @return           The color object. The color information represented by this 
+                   object is in the device RGB colorspace.
+ */
++ (UIColor *)colorWithHue:(CGFloat)hue
+               saturation:(CGFloat)saturation
+                lightness:(CGFloat)lightness
+                    alpha:(CGFloat)alpha;
+
+/**
+ Creates and returns a color object using the specified opacity
+ and CMYK color space component values.
+ 
+ @param cyan    The cyan component of the color object in the CMYK color space,
+                specified as a value from 0.0 to 1.0.
+ 
+ @param magenta The magenta component of the color object in the CMYK color space,
+                specified as a value from 0.0 to 1.0.
+ 
+ @param yellow  The yellow component of the color object in the CMYK color space,
+                specified as a value from 0.0 to 1.0.
+ 
+ @param black   The black component of the color object in the CMYK color space,
+                specified as a value from 0.0 to 1.0.
+ 
+ @param alpha   The opacity value of the color object,
+                specified as a value from 0.0 to 1.0.
+ 
+ @return        The color object. The color information represented by this 
+                object is in the device RGB colorspace.
+ */
++ (UIColor *)colorWithCyan:(CGFloat)cyan
+                   magenta:(CGFloat)magenta
+                    yellow:(CGFloat)yellow
+                     black:(CGFloat)black
+                     alpha:(CGFloat)alpha;
+
+/**
+ Creates and returns a color object using the hex RGB color values.
+ 
+ @param rgbValue  The rgb value such as 0x66ccff.
+ 
+ @return          The color object. The color information represented by this
+                  object is in the device RGB colorspace.
+ */
++ (UIColor *)colorWithRGB:(uint32_t)rgbValue;
+
+/**
+ Creates and returns a color object using the hex RGBA color values.
+ 
+ @param rgbaValue  The rgb value such as 0x66ccffff.
+ 
+ @return           The color object. The color information represented by this 
+                   object is in the device RGB colorspace.
+ */
++ (UIColor *)colorWithRGBA:(uint32_t)rgbaValue;
+
+/**
+ Creates and returns a color object using the specified opacity and RGB hex value.
+ 
+ @param rgbValue  The rgb value such as 0x66CCFF.
+ 
+ @param alpha     The opacity value of the color object,
+                  specified as a value from 0.0 to 1.0.
+ 
+ @return          The color object. The color information represented by this 
+                  object is in the device RGB colorspace.
+ */
++ (UIColor *)colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha;
+
+/**
+ Creates and returns a color object from hex string.
+ 
+ @discussion:
+ Valid format: #RGB #RGBA #RRGGBB #RRGGBBAA 0xRGB ...
+ The `#` or "0x" sign is not required.
+ The alpha will be set to 1.0 if there is no alpha component.
+ It will return nil when an error occurs in parsing.
+ 
+ Example: @"0xF0F", @"66ccff", @"#66CCFF88"
+ 
+ @param hexStr  The hex string value for the new color.
+ 
+ @return        An UIColor object from string, or nil if an error occurs.
+ */
++ (nullable UIColor *)colorWithHexString:(NSString *)hexStr;
+
+/**
+ Creates and returns a color object by add new color.
+ 
+ @param add        the color added
+ 
+ @param blendMode  add color blend mode
+ */
+- (UIColor *)colorByAddColor:(UIColor *)add blendMode:(CGBlendMode)blendMode;
+
+/**
+ Creates and returns a color object by change components.
+ 
+ @param hueDelta         the hue change delta specified as a value 
+                         from -1.0 to 1.0. 0 means no change.
+ 
+ @param saturationDelta  the saturation change delta specified as a value 
+                         from -1.0 to 1.0. 0 means no change.
+ 
+ @param brightnessDelta  the brightness change delta specified as a value 
+                         from -1.0 to 1.0. 0 means no change.
+ 
+ @param alphaDelta       the alpha change delta specified as a value 
+                         from -1.0 to 1.0. 0 means no change.
+ */
+- (UIColor *)colorByChangeHue:(CGFloat)hueDelta
+                   saturation:(CGFloat)saturationDelta
+                   brightness:(CGFloat)brightnessDelta
+                        alpha:(CGFloat)alphaDelta;
+
+
+#pragma mark - Get color's description
+///=============================================================================
+/// @name Get color's description
+///=============================================================================
+
+/**
+ Returns the rgb value in hex.
+ @return hex value of RGB,such as 0x66ccff.
+ */
+- (uint32_t)rgbValue;
+
+/**
+ Returns the rgba value in hex.
+ 
+ @return hex value of RGBA,such as 0x66ccffff.
+ */
+- (uint32_t)rgbaValue;
+
+/**
+ Returns the color's RGB value as a hex string (lowercase).
+ Such as @"0066cc".
+ 
+ It will return nil when the color space is not RGB
+ 
+ @return The color's value as a hex string.
+ */
+- (nullable NSString *)hexString;
+
+/**
+ Returns the color's RGBA value as a hex string (lowercase).
+ Such as @"0066ccff".
+ 
+ It will return nil when the color space is not RGBA
+ 
+ @return The color's value as a hex string.
+ */
+- (nullable NSString *)hexStringWithAlpha;
+
+
+#pragma mark - Retrieving Color Information
+///=============================================================================
+/// @name Retrieving Color Information
+///=============================================================================
+
+/**
+ Returns the components that make up the color in the HSL color space.
+ 
+ @param hue         On return, the hue component of the color object,
+                    specified as a value between 0.0 and 1.0.
+ 
+ @param saturation  On return, the saturation component of the color object,
+                    specified as a value between 0.0 and 1.0.
+ 
+ @param lightness   On return, the lightness component of the color object,
+                    specified as a value between 0.0 and 1.0.
+ 
+ @param alpha       On return, the alpha component of the color object,
+                    specified as a value between 0.0 and 1.0.
+ 
+ @return            YES if the color could be converted, NO otherwise.
+ */
+- (BOOL)getHue:(CGFloat *)hue
+    saturation:(CGFloat *)saturation
+     lightness:(CGFloat *)lightness
+         alpha:(CGFloat *)alpha;
+
+/**
+ Returns the components that make up the color in the CMYK color space.
+ 
+ @param cyan     On return, the cyan component of the color object,
+                 specified as a value between 0.0 and 1.0.
+ 
+ @param magenta  On return, the magenta component of the color object,
+                 specified as a value between 0.0 and 1.0.
+ 
+ @param yellow   On return, the yellow component of the color object,
+                 specified as a value between 0.0 and 1.0.
+ 
+ @param black    On return, the black component of the color object,
+                 specified as a value between 0.0 and 1.0.
+ 
+ @param alpha    On return, the alpha component of the color object,
+                 specified as a value between 0.0 and 1.0.
+ 
+ @return         YES if the color could be converted, NO otherwise.
+ */
+- (BOOL)getCyan:(CGFloat *)cyan
+        magenta:(CGFloat *)magenta
+         yellow:(CGFloat *)yellow
+          black:(CGFloat *)black
+          alpha:(CGFloat *)alpha;
+
+/**
+ The color's red component value in RGB color space.
+ The value of this property is a float in the range `0.0` to `1.0`.
+ */
+@property (nonatomic, readonly) CGFloat red;
+
+/**
+ The color's green component value in RGB color space.
+ The value of this property is a float in the range `0.0` to `1.0`.
+ */
+@property (nonatomic, readonly) CGFloat green;
+
+/**
+ The color's blue component value in RGB color space.
+ The value of this property is a float in the range `0.0` to `1.0`.
+ */
+@property (nonatomic, readonly) CGFloat blue;
+
+/**
+ The color's hue component value in HSB color space.
+ The value of this property is a float in the range `0.0` to `1.0`.
+ */
+@property (nonatomic, readonly) CGFloat hue;
+
+/**
+ The color's saturation component value in HSB color space.
+ The value of this property is a float in the range `0.0` to `1.0`.
+ */
+@property (nonatomic, readonly) CGFloat saturation;
+
+/**
+ The color's brightness component value in HSB color space.
+ The value of this property is a float in the range `0.0` to `1.0`.
+ */
+@property (nonatomic, readonly) CGFloat brightness;
+
+/**
+ The color's alpha component value.
+ The value of this property is a float in the range `0.0` to `1.0`.
+ */
+@property (nonatomic, readonly) CGFloat alpha;
+
+/**
+ The color's colorspace model.
+ */
+@property (nonatomic, readonly) CGColorSpaceModel colorSpaceModel;
+
+/**
+ Readable colorspace string.
+ */
+@property (nullable, nonatomic, readonly) NSString *colorSpaceString;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 474 - 0
YYKit/Base/UIKit/UIColor+YYAdd.m

@@ -0,0 +1,474 @@
+//
+//  UIColor+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIColor+YYAdd.h"
+#import "NSString+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(UIColor_YYAdd)
+
+
+#define CLAMP_COLOR_VALUE(v) (v) = (v) < 0 ? 0 : (v) > 1 ? 1 : (v)
+
+void YY_RGB2HSL(CGFloat r, CGFloat g, CGFloat b,
+                CGFloat *h, CGFloat *s, CGFloat *l) {
+    CLAMP_COLOR_VALUE(r);
+    CLAMP_COLOR_VALUE(g);
+    CLAMP_COLOR_VALUE(b);
+    
+    CGFloat max, min, delta, sum;
+    max = fmaxf(r, fmaxf(g, b));
+    min = fminf(r, fminf(g, b));
+    delta = max - min;
+    sum = max + min;
+    
+    *l = sum / 2;           // Lightness
+    if (delta == 0) {       // No Saturation, so Hue is undefined (achromatic)
+        *h = *s = 0;
+        return;
+    }
+    *s = delta / (sum < 1 ? sum : 2 - sum);             // Saturation
+    if (r == max) *h = (g - b) / delta / 6;             // color between y & m
+    else if (g == max) *h = (2 + (b - r) / delta) / 6;  // color between c & y
+    else *h = (4 + (r - g) / delta) / 6;                // color between m & y
+    if (*h < 0) *h += 1;
+}
+
+void YY_HSL2RGB(CGFloat h, CGFloat s, CGFloat l,
+                CGFloat *r, CGFloat *g, CGFloat *b) {
+    CLAMP_COLOR_VALUE(h);
+    CLAMP_COLOR_VALUE(s);
+    CLAMP_COLOR_VALUE(l);
+    
+    if (s == 0) { // No Saturation, Hue is undefined (achromatic)
+        *r = *g = *b = l;
+        return;
+    }
+    
+    CGFloat q;
+    q = (l <= 0.5) ? (l * (1 + s)) : (l + s - (l * s));
+    if (q <= 0) {
+        *r = *g = *b = 0.0;
+    } else {
+        *r = *g = *b = 0;
+        int sextant;
+        CGFloat m, sv, fract, vsf, mid1, mid2;
+        m = l + l - q;
+        sv = (q - m) / q;
+        if (h == 1) h = 0;
+        h *= 6.0;
+        sextant = h;
+        fract = h - sextant;
+        vsf = q * sv * fract;
+        mid1 = m + vsf;
+        mid2 = q - vsf;
+        switch (sextant) {
+            case 0: *r = q; *g = mid1; *b = m; break;
+            case 1: *r = mid2; *g = q; *b = m; break;
+            case 2: *r = m; *g = q; *b = mid1; break;
+            case 3: *r = m; *g = mid2; *b = q; break;
+            case 4: *r = mid1; *g = m; *b = q; break;
+            case 5: *r = q; *g = m; *b = mid2; break;
+        }
+    }
+}
+
+void YY_RGB2HSB(CGFloat r, CGFloat g, CGFloat b,
+                CGFloat *h, CGFloat *s, CGFloat *v) {
+    CLAMP_COLOR_VALUE(r);
+    CLAMP_COLOR_VALUE(g);
+    CLAMP_COLOR_VALUE(b);
+    
+    CGFloat max, min, delta;
+    max = fmax(r, fmax(g, b));
+    min = fmin(r, fmin(g, b));
+    delta = max - min;
+    
+    *v = max;               // Brightness
+    if (delta == 0) {       // No Saturation, so Hue is undefined (achromatic)
+        *h = *s = 0;
+        return;
+    }
+    *s = delta / max;       // Saturation
+    
+    if (r == max) *h = (g - b) / delta / 6;             // color between y & m
+    else if (g == max) *h = (2 + (b - r) / delta) / 6;  // color between c & y
+    else *h = (4 + (r - g) / delta) / 6;                // color between m & c
+    if (*h < 0) *h += 1;
+}
+
+void YY_HSB2RGB(CGFloat h, CGFloat s, CGFloat v,
+                CGFloat *r, CGFloat *g, CGFloat *b) {
+    CLAMP_COLOR_VALUE(h);
+    CLAMP_COLOR_VALUE(s);
+    CLAMP_COLOR_VALUE(v);
+    
+    if (s == 0) {
+        *r = *g = *b = v; // No Saturation, so Hue is undefined (Achromatic)
+    } else {
+        int sextant;
+        CGFloat f, p, q, t;
+        if (h == 1) h = 0;
+        h *= 6;
+        sextant = floor(h);
+        f = h - sextant;
+        p = v * (1 - s);
+        q = v * (1 - s * f);
+        t = v * (1 - s * (1 - f));
+        switch (sextant) {
+            case 0: *r = v; *g = t; *b = p; break;
+            case 1: *r = q; *g = v; *b = p; break;
+            case 2: *r = p; *g = v; *b = t; break;
+            case 3: *r = p; *g = q; *b = v; break;
+            case 4: *r = t; *g = p; *b = v; break;
+            case 5: *r = v; *g = p; *b = q; break;
+        }
+    }
+}
+
+void YY_RGB2CMYK(CGFloat r, CGFloat g, CGFloat b,
+                 CGFloat *c, CGFloat *m, CGFloat *y, CGFloat *k) {
+    CLAMP_COLOR_VALUE(r);
+    CLAMP_COLOR_VALUE(g);
+    CLAMP_COLOR_VALUE(b);
+    
+    *c = 1 - r;
+    *m = 1 - g;
+    *y = 1 - b;
+    *k = fmin(*c, fmin(*m, *y));
+    
+    if (*k == 1) {
+        *c = *m = *y = 0;   // Pure black
+    } else {
+        *c = (*c - *k) / (1 - *k);
+        *m = (*m - *k) / (1 - *k);
+        *y = (*y - *k) / (1 - *k);
+    }
+}
+
+void YY_CMYK2RGB(CGFloat c, CGFloat m, CGFloat y, CGFloat k,
+                 CGFloat *r, CGFloat *g, CGFloat *b) {
+    CLAMP_COLOR_VALUE(c);
+    CLAMP_COLOR_VALUE(m);
+    CLAMP_COLOR_VALUE(y);
+    CLAMP_COLOR_VALUE(k);
+    
+    *r = (1 - c) * (1 - k);
+    *g = (1 - m) * (1 - k);
+    *b = (1 - y) * (1 - k);
+}
+
+void YY_HSB2HSL(CGFloat h, CGFloat s, CGFloat b,
+                CGFloat *hh, CGFloat *ss, CGFloat *ll) {
+    CLAMP_COLOR_VALUE(h);
+    CLAMP_COLOR_VALUE(s);
+    CLAMP_COLOR_VALUE(b);
+    
+    *hh = h;
+    *ll = (2 - s) * b / 2;
+    if (*ll <= 0.5) {
+        *ss = (s) / ((2 - s));
+    } else {
+        *ss = (s * b) / (2 - (2 - s) * b);
+    }
+}
+
+void YY_HSL2HSB(CGFloat h, CGFloat s, CGFloat l,
+                CGFloat *hh, CGFloat *ss, CGFloat *bb) {
+    CLAMP_COLOR_VALUE(h);
+    CLAMP_COLOR_VALUE(s);
+    CLAMP_COLOR_VALUE(l);
+    
+    *hh = h;
+    if (l <= 0.5) {
+        *bb = (s + 1) * l;
+        *ss = (2 * s) / (s + 1);
+    } else {
+        *bb = l + s * (1 - l);
+        *ss = (2 * s * (1 - l)) / *bb;
+    }
+}
+
+#undef CLAMP_COLOR_VALUE
+
+@implementation UIColor (YYAdd)
+
++ (UIColor *)colorWithHue:(CGFloat)hue
+               saturation:(CGFloat)saturation
+                lightness:(CGFloat)lightness
+                    alpha:(CGFloat)alpha {
+    CGFloat r, g, b;
+    YY_HSL2RGB(hue, saturation, lightness, &r, &g, &b);
+    return [UIColor colorWithRed:r green:g blue:b alpha:alpha];
+}
++ (UIColor *)colorWithCyan:(CGFloat)cyan
+                   magenta:(CGFloat)magenta
+                    yellow:(CGFloat)yellow
+                     black:(CGFloat)black
+                     alpha:(CGFloat)alpha {
+    CGFloat r, g, b;
+    YY_CMYK2RGB(cyan, magenta, yellow, black, &r, &g, &b);
+    return [UIColor colorWithRed:r green:g blue:b alpha:alpha];
+}
+
++ (UIColor *)colorWithRGB:(uint32_t)rgbValue {
+    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0f
+                           green:((rgbValue & 0xFF00) >> 8) / 255.0f
+                            blue:(rgbValue & 0xFF) / 255.0f
+                           alpha:1];
+}
+
++ (UIColor *)colorWithRGBA:(uint32_t)rgbaValue {
+    return [UIColor colorWithRed:((rgbaValue & 0xFF000000) >> 24) / 255.0f
+                           green:((rgbaValue & 0xFF0000) >> 16) / 255.0f
+                            blue:((rgbaValue & 0xFF00) >> 8) / 255.0f
+                           alpha:(rgbaValue & 0xFF) / 255.0f];
+}
+
++ (UIColor *)colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha {
+    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0f
+                           green:((rgbValue & 0xFF00) >> 8) / 255.0f
+                            blue:(rgbValue & 0xFF) / 255.0f
+                           alpha:alpha];
+}
+
+- (uint32_t)rgbValue {
+    CGFloat r = 0, g = 0, b = 0, a = 0;
+    [self getRed:&r green:&g blue:&b alpha:&a];
+    int8_t red = r * 255;
+    uint8_t green = g * 255;
+    uint8_t blue = b * 255;
+    return (red << 16) + (green << 8) + blue;
+}
+
+- (uint32_t)rgbaValue {
+    CGFloat r = 0, g = 0, b = 0, a = 0;
+    [self getRed:&r green:&g blue:&b alpha:&a];
+    int8_t red = r * 255;
+    uint8_t green = g * 255;
+    uint8_t blue = b * 255;
+    uint8_t alpha = a * 255;
+    return (red << 24) + (green << 16) + (blue << 8) + alpha;
+}
+
+static inline NSUInteger hexStrToInt(NSString *str) {
+    uint32_t result = 0;
+    sscanf([str UTF8String], "%X", &result);
+    return result;
+}
+
+static BOOL hexStrToRGBA(NSString *str,
+                         CGFloat *r, CGFloat *g, CGFloat *b, CGFloat *a) {
+    str = [[str stringByTrim] uppercaseString];
+    if ([str hasPrefix:@"#"]) {
+        str = [str substringFromIndex:1];
+    } else if ([str hasPrefix:@"0X"]) {
+        str = [str substringFromIndex:2];
+    }
+    
+    NSUInteger length = [str length];
+    //         RGB            RGBA          RRGGBB        RRGGBBAA
+    if (length != 3 && length != 4 && length != 6 && length != 8) {
+        return NO;
+    }
+    
+    //RGB,RGBA,RRGGBB,RRGGBBAA
+    if (length < 5) {
+        *r = hexStrToInt([str substringWithRange:NSMakeRange(0, 1)]) / 255.0f;
+        *g = hexStrToInt([str substringWithRange:NSMakeRange(1, 1)]) / 255.0f;
+        *b = hexStrToInt([str substringWithRange:NSMakeRange(2, 1)]) / 255.0f;
+        if (length == 4)  *a = hexStrToInt([str substringWithRange:NSMakeRange(3, 1)]) / 255.0f;
+        else *a = 1;
+    } else {
+        *r = hexStrToInt([str substringWithRange:NSMakeRange(0, 2)]) / 255.0f;
+        *g = hexStrToInt([str substringWithRange:NSMakeRange(2, 2)]) / 255.0f;
+        *b = hexStrToInt([str substringWithRange:NSMakeRange(4, 2)]) / 255.0f;
+        if (length == 8) *a = hexStrToInt([str substringWithRange:NSMakeRange(6, 2)]) / 255.0f;
+        else *a = 1;
+    }
+    return YES;
+}
+
++ (instancetype)colorWithHexString:(NSString *)hexStr {
+    CGFloat r, g, b, a;
+    if (hexStrToRGBA(hexStr, &r, &g, &b, &a)) {
+        return [UIColor colorWithRed:r green:g blue:b alpha:a];
+    }
+    return nil;
+}
+
+- (NSString *)hexString {
+    return [self hexStringWithAlpha:NO];
+}
+
+- (NSString *)hexStringWithAlpha {
+    return [self hexStringWithAlpha:YES];
+}
+
+- (NSString *)hexStringWithAlpha:(BOOL)withAlpha {
+    CGColorRef color = self.CGColor;
+    size_t count = CGColorGetNumberOfComponents(color);
+    const CGFloat *components = CGColorGetComponents(color);
+    static NSString *stringFormat = @"%02x%02x%02x";
+    NSString *hex = nil;
+    if (count == 2) {
+        NSUInteger white = (NSUInteger)(components[0] * 255.0f);
+        hex = [NSString stringWithFormat:stringFormat, white, white, white];
+    } else if (count == 4) {
+        hex = [NSString stringWithFormat:stringFormat,
+               (NSUInteger)(components[0] * 255.0f),
+               (NSUInteger)(components[1] * 255.0f),
+               (NSUInteger)(components[2] * 255.0f)];
+    }
+    
+    if (hex && withAlpha) {
+        hex = [hex stringByAppendingFormat:@"%02lx",
+               (unsigned long)(self.alpha * 255.0 + 0.5)];
+    }
+    return hex;
+}
+
+- (UIColor *)colorByAddColor:(UIColor *)add blendMode:(CGBlendMode)blendMode {
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
+    uint8_t pixel[4] = { 0 };
+    CGContextRef context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, bitmapInfo);
+    CGContextSetFillColorWithColor(context, self.CGColor);
+    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
+    CGContextSetBlendMode(context, blendMode);
+    CGContextSetFillColorWithColor(context, add.CGColor);
+    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
+    CGContextRelease(context);
+    CGColorSpaceRelease(colorSpace);
+    return [UIColor colorWithRed:pixel[0] / 255.0f green:pixel[1] / 255.0f blue:pixel[2] / 255.0f alpha:pixel[3] / 255.0f];
+}
+
+- (UIColor *)colorByChangeHue:(CGFloat)h saturation:(CGFloat)s brightness:(CGFloat)b alpha:(CGFloat)a {
+    CGFloat hh, ss, bb, aa;
+    if (![self getHue:&hh saturation:&ss brightness:&bb alpha:&aa]) {
+        return self;
+    }
+    hh += h;
+    ss += s;
+    bb += b;
+    aa += a;
+    hh -= (int)hh;
+    hh = hh < 0 ? hh + 1 : hh;
+    ss = ss < 0 ? 0 : ss > 1 ? 1 : ss;
+    bb = bb < 0 ? 0 : bb > 1 ? 1 : bb;
+    aa = aa < 0 ? 0 : aa > 1 ? 1 : aa;
+    return [UIColor colorWithHue:hh saturation:ss brightness:bb alpha:aa];
+}
+
+- (BOOL)getHue:(CGFloat *)hue
+    saturation:(CGFloat *)saturation
+     lightness:(CGFloat *)lightness
+         alpha:(CGFloat *)alpha {
+    CGFloat r, g, b, a;
+    if (![self getRed:&r green:&g blue:&b alpha:&a]) {
+        return NO;
+    }
+    YY_RGB2HSL(r, g, b, hue, saturation, lightness);
+    *alpha = a;
+    return YES;
+}
+
+- (BOOL)getCyan:(CGFloat *)cyan
+        magenta:(CGFloat *)magenta
+         yellow:(CGFloat *)yellow
+          black:(CGFloat *)black
+          alpha:(CGFloat *)alpha {
+    CGFloat r, g, b, a;
+    if (![self getRed:&r green:&g blue:&b alpha:&a]) {
+        return NO;
+    }
+    YY_RGB2CMYK(r, g, b, cyan, magenta, yellow, black);
+    *alpha = a;
+    return YES;
+}
+
+- (CGFloat)red {
+    CGFloat r = 0, g, b, a;
+    [self getRed:&r green:&g blue:&b alpha:&a];
+    return r;
+}
+
+- (CGFloat)green {
+    CGFloat r, g = 0, b, a;
+    [self getRed:&r green:&g blue:&b alpha:&a];
+    return g;
+}
+
+- (CGFloat)blue {
+    CGFloat r, g, b = 0, a;
+    [self getRed:&r green:&g blue:&b alpha:&a];
+    return b;
+}
+
+- (CGFloat)alpha {
+    return CGColorGetAlpha(self.CGColor);
+}
+
+- (CGFloat)hue {
+    CGFloat h = 0, s, b, a;
+    [self getHue:&h saturation:&s brightness:&b alpha:&a];
+    return h;
+}
+
+- (CGFloat)saturation {
+    CGFloat h, s = 0, b, a;
+    [self getHue:&h saturation:&s brightness:&b alpha:&a];
+    return s;
+}
+
+- (CGFloat)brightness {
+    CGFloat h, s, b = 0, a;
+    [self getHue:&h saturation:&s brightness:&b alpha:&a];
+    return b;
+}
+
+- (CGColorSpaceModel)colorSpaceModel {
+    return CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor));
+}
+
+- (NSString *)colorSpaceString {
+    CGColorSpaceModel model =  CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor));
+    switch (model) {
+        case kCGColorSpaceModelUnknown:
+            return @"kCGColorSpaceModelUnknown";
+            
+        case kCGColorSpaceModelMonochrome:
+            return @"kCGColorSpaceModelMonochrome";
+            
+        case kCGColorSpaceModelRGB:
+            return @"kCGColorSpaceModelRGB";
+            
+        case kCGColorSpaceModelCMYK:
+            return @"kCGColorSpaceModelCMYK";
+            
+        case kCGColorSpaceModelLab:
+            return @"kCGColorSpaceModelLab";
+            
+        case kCGColorSpaceModelDeviceN:
+            return @"kCGColorSpaceModelDeviceN";
+            
+        case kCGColorSpaceModelIndexed:
+            return @"kCGColorSpaceModelIndexed";
+            
+        case kCGColorSpaceModelPattern:
+            return @"kCGColorSpaceModelPattern";
+            
+        default:
+            return @"ColorSpaceInvalid";
+    }
+}
+
+@end

+ 78 - 0
YYKit/Base/UIKit/UIControl+YYAdd.h

@@ -0,0 +1,78 @@
+//
+//  UIControl+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/5.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIControl`.
+ */
+@interface UIControl (YYAdd)
+
+/**
+ Removes all targets and actions for a particular event (or events)
+ from an internal dispatch table.
+ */
+- (void)removeAllTargets;
+
+/**
+ Adds or replaces a target and action for a particular event (or events)
+ to an internal dispatch table.
+ 
+ @param target         The target object—that is, the object to which the
+                       action message is sent. If this is nil, the responder
+                       chain is searched for an object willing to respond to the
+                       action message.
+ 
+ @param action         A selector identifying an action message. It cannot be NULL.
+ 
+ @param controlEvents  A bitmask specifying the control events for which the
+                       action message is sent.
+ */
+- (void)setTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
+
+/**
+ Adds a block for a particular event (or events) to an internal dispatch table.
+ It will cause a strong reference to @a block.
+ 
+ @param block          The block which is invoked then the action message is
+                       sent  (cannot be nil). The block is retained.
+ 
+ @param controlEvents  A bitmask specifying the control events for which the
+                       action message is sent.
+ */
+- (void)addBlockForControlEvents:(UIControlEvents)controlEvents block:(void (^)(id sender))block;
+
+/**
+ Adds or replaces a block for a particular event (or events) to an internal
+ dispatch table. It will cause a strong reference to @a block.
+ 
+ @param block          The block which is invoked then the action message is
+                       sent (cannot be nil). The block is retained.
+ 
+ @param controlEvents  A bitmask specifying the control events for which the
+                       action message is sent.
+ */
+- (void)setBlockForControlEvents:(UIControlEvents)controlEvents block:(void (^)(id sender))block;
+
+/**
+ Removes all blocks for a particular event (or events) from an internal
+ dispatch table.
+ 
+ @param controlEvents  A bitmask specifying the control events for which the
+                       action message is sent.
+ */
+- (void)removeAllBlocksForControlEvents:(UIControlEvents)controlEvents;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 118 - 0
YYKit/Base/UIKit/UIControl+YYAdd.m

@@ -0,0 +1,118 @@
+//
+//  UIControl+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/5.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIControl+YYAdd.h"
+#import "YYKitMacro.h"
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(UIControl_YYAdd)
+
+
+static const int block_key;
+
+@interface _YYUIControlBlockTarget : NSObject
+
+@property (nonatomic, copy) void (^block)(id sender);
+@property (nonatomic, assign) UIControlEvents events;
+
+- (id)initWithBlock:(void (^)(id sender))block events:(UIControlEvents)events;
+- (void)invoke:(id)sender;
+
+@end
+
+@implementation _YYUIControlBlockTarget
+
+- (id)initWithBlock:(void (^)(id sender))block events:(UIControlEvents)events {
+    self = [super init];
+    if (self) {
+        _block = [block copy];
+        _events = events;
+    }
+    return self;
+}
+
+- (void)invoke:(id)sender {
+    if (_block) _block(sender);
+}
+
+@end
+
+
+
+@implementation UIControl (YYAdd)
+
+- (void)removeAllTargets {
+    [[self allTargets] enumerateObjectsUsingBlock: ^(id object, BOOL *stop) {
+        [self removeTarget:object action:NULL forControlEvents:UIControlEventAllEvents];
+    }];
+    [[self _yy_allUIControlBlockTargets] removeAllObjects];
+}
+
+- (void)setTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents {
+    if (!target || !action || !controlEvents) return;
+    NSSet *targets = [self allTargets];
+    for (id currentTarget in targets) {
+        NSArray *actions = [self actionsForTarget:currentTarget forControlEvent:controlEvents];
+        for (NSString *currentAction in actions) {
+            [self removeTarget:currentTarget action:NSSelectorFromString(currentAction)
+                forControlEvents:controlEvents];
+        }
+    }
+    [self addTarget:target action:action forControlEvents:controlEvents];
+}
+
+- (void)addBlockForControlEvents:(UIControlEvents)controlEvents
+                           block:(void (^)(id sender))block {
+    if (!controlEvents) return;
+    _YYUIControlBlockTarget *target = [[_YYUIControlBlockTarget alloc]
+                                       initWithBlock:block events:controlEvents];
+    [self addTarget:target action:@selector(invoke:) forControlEvents:controlEvents];
+    NSMutableArray *targets = [self _yy_allUIControlBlockTargets];
+    [targets addObject:target];
+}
+
+- (void)setBlockForControlEvents:(UIControlEvents)controlEvents
+                           block:(void (^)(id sender))block {
+    [self removeAllBlocksForControlEvents:UIControlEventAllEvents];
+    [self addBlockForControlEvents:controlEvents block:block];
+}
+
+- (void)removeAllBlocksForControlEvents:(UIControlEvents)controlEvents {
+    if (!controlEvents) return;
+    
+    NSMutableArray *targets = [self _yy_allUIControlBlockTargets];
+    NSMutableArray *removes = [NSMutableArray array];
+    for (_YYUIControlBlockTarget *target in targets) {
+        if (target.events & controlEvents) {
+            UIControlEvents newEvent = target.events & (~controlEvents);
+            if (newEvent) {
+                [self removeTarget:target action:@selector(invoke:) forControlEvents:target.events];
+                target.events = newEvent;
+                [self addTarget:target action:@selector(invoke:) forControlEvents:target.events];
+            } else {
+                [self removeTarget:target action:@selector(invoke:) forControlEvents:target.events];
+                [removes addObject:target];
+            }
+        }
+    }
+    [targets removeObjectsInArray:removes];
+}
+
+- (NSMutableArray *)_yy_allUIControlBlockTargets {
+    NSMutableArray *targets = objc_getAssociatedObject(self, &block_key);
+    if (!targets) {
+        targets = [NSMutableArray array];
+        objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return targets;
+}
+
+@end

+ 193 - 0
YYKit/Base/UIKit/UIDevice+YYAdd.h

@@ -0,0 +1,193 @@
+//
+//  UIDevice+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIDevice`.
+ */
+@interface UIDevice (YYAdd)
+
+
+#pragma mark - Device Information
+///=============================================================================
+/// @name Device Information
+///=============================================================================
+
+/// Device system version (e.g. 8.1)
++ (double)systemVersion;
+
+/// Whether the device is iPad/iPad mini.
+@property (nonatomic, readonly) BOOL isPad;
+
+/// Whether the device is a simulator.
+@property (nonatomic, readonly) BOOL isSimulator;
+
+/// Whether the device is jailbroken.
+@property (nonatomic, readonly) BOOL isJailbroken;
+
+/// Wherher the device can make phone calls.
+@property (nonatomic, readonly) BOOL canMakePhoneCalls NS_EXTENSION_UNAVAILABLE_IOS("");
+
+/// The device's machine model.  e.g. "iPhone6,1" "iPad4,6"
+/// @see http://theiphonewiki.com/wiki/Models
+@property (nullable, nonatomic, readonly) NSString *machineModel;
+
+/// The device's machine model name. e.g. "iPhone 5s" "iPad mini 2"
+/// @see http://theiphonewiki.com/wiki/Models
+@property (nullable, nonatomic, readonly) NSString *machineModelName;
+
+/// The System's startup time.
+@property (nonatomic, readonly) NSDate *systemUptime;
+
+
+#pragma mark - Network Information
+///=============================================================================
+/// @name Network Information
+///=============================================================================
+
+/// WIFI IP address of this device (can be nil). e.g. @"192.168.1.111"
+@property (nullable, nonatomic, readonly) NSString *ipAddressWIFI;
+
+/// Cell IP address of this device (can be nil). e.g. @"10.2.2.222"
+@property (nullable, nonatomic, readonly) NSString *ipAddressCell;
+
+
+/**
+ Network traffic type:
+ 
+ WWAN: Wireless Wide Area Network.
+       For example: 3G/4G.
+ 
+ WIFI: Wi-Fi.
+ 
+ AWDL: Apple Wireless Direct Link (peer-to-peer connection).
+       For exmaple: AirDrop, AirPlay, GameKit.
+ */
+typedef NS_OPTIONS(NSUInteger, YYNetworkTrafficType) {
+    YYNetworkTrafficTypeWWANSent     = 1 << 0,
+    YYNetworkTrafficTypeWWANReceived = 1 << 1,
+    YYNetworkTrafficTypeWIFISent     = 1 << 2,
+    YYNetworkTrafficTypeWIFIReceived = 1 << 3,
+    YYNetworkTrafficTypeAWDLSent     = 1 << 4,
+    YYNetworkTrafficTypeAWDLReceived = 1 << 5,
+    
+    YYNetworkTrafficTypeWWAN = YYNetworkTrafficTypeWWANSent | YYNetworkTrafficTypeWWANReceived,
+    YYNetworkTrafficTypeWIFI = YYNetworkTrafficTypeWIFISent | YYNetworkTrafficTypeWIFIReceived,
+    YYNetworkTrafficTypeAWDL = YYNetworkTrafficTypeAWDLSent | YYNetworkTrafficTypeAWDLReceived,
+    
+    YYNetworkTrafficTypeALL = YYNetworkTrafficTypeWWAN |
+                              YYNetworkTrafficTypeWIFI |
+                              YYNetworkTrafficTypeAWDL,
+};
+
+/**
+ Get device network traffic bytes.
+ 
+ @discussion This is a counter since the device's last boot time.
+ Usage:
+ 
+     uint64_t bytes = [[UIDevice currentDevice] getNetworkTrafficBytes:YYNetworkTrafficTypeALL];
+     NSTimeInterval time = CACurrentMediaTime();
+     
+     uint64_t bytesPerSecond = (bytes - _lastBytes) / (time - _lastTime);
+     
+     _lastBytes = bytes;
+     _lastTime = time;
+ 
+ 
+ @param type traffic types
+ @return bytes counter.
+ */
+- (uint64_t)getNetworkTrafficBytes:(YYNetworkTrafficType)types;
+
+
+#pragma mark - Disk Space
+///=============================================================================
+/// @name Disk Space
+///=============================================================================
+
+/// Total disk space in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t diskSpace;
+
+/// Free disk space in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t diskSpaceFree;
+
+/// Used disk space in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t diskSpaceUsed;
+
+
+#pragma mark - Memory Information
+///=============================================================================
+/// @name Memory Information
+///=============================================================================
+
+/// Total physical memory in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryTotal;
+
+/// Used (active + inactive + wired) memory in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryUsed;
+
+/// Free memory in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryFree;
+
+/// Acvite memory in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryActive;
+
+/// Inactive memory in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryInactive;
+
+/// Wired memory in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryWired;
+
+/// Purgable memory in byte. (-1 when error occurs)
+@property (nonatomic, readonly) int64_t memoryPurgable;
+
+#pragma mark - CPU Information
+///=============================================================================
+/// @name CPU Information
+///=============================================================================
+
+/// Avaliable CPU processor count.
+@property (nonatomic, readonly) NSUInteger cpuCount;
+
+/// Current CPU usage, 1.0 means 100%. (-1 when error occurs)
+@property (nonatomic, readonly) float cpuUsage;
+
+/// Current CPU usage per processor (array of NSNumber), 1.0 means 100%. (nil when error occurs)
+@property (nullable, nonatomic, readonly) NSArray<NSNumber *> *cpuUsagePerProcessor;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+
+#ifndef kSystemVersion
+#define kSystemVersion [UIDevice systemVersion]
+#endif
+
+#ifndef kiOS6Later
+#define kiOS6Later (kSystemVersion >= 6)
+#endif
+
+#ifndef kiOS7Later
+#define kiOS7Later (kSystemVersion >= 7)
+#endif
+
+#ifndef kiOS8Later
+#define kiOS8Later (kSystemVersion >= 8)
+#endif
+
+#ifndef kiOS9Later
+#define kiOS9Later (kSystemVersion >= 9)
+#endif

+ 515 - 0
YYKit/Base/UIKit/UIDevice+YYAdd.m

@@ -0,0 +1,515 @@
+//
+//  UIDevice+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIDevice+YYAdd.h"
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+#include <net/if.h>
+#include <net/if_dl.h>
+#include <mach/mach.h>
+#include <arpa/inet.h>
+#include <ifaddrs.h>
+#import "YYKitMacro.h"
+#import "NSString+YYAdd.h"
+
+YYSYNTH_DUMMY_CLASS(UIDevice_YYAdd)
+
+
+@implementation UIDevice (YYAdd)
+
++ (double)systemVersion {
+    static double version;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        version = [UIDevice currentDevice].systemVersion.doubleValue;
+    });
+    return version;
+}
+
+- (BOOL)isPad {
+    static dispatch_once_t one;
+    static BOOL pad;
+    dispatch_once(&one, ^{
+        pad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
+    });
+    return pad;
+}
+
+- (BOOL)isSimulator {
+#if TARGET_OS_SIMULATOR
+    return YES;
+#else
+    return NO;
+#endif
+}
+
+- (BOOL)isJailbroken {
+    if ([self isSimulator]) return NO; // Dont't check simulator
+    
+    // iOS9 URL Scheme query changed ...
+    // NSURL *cydiaURL = [NSURL URLWithString:@"cydia://package"];
+    // if ([[UIApplication sharedApplication] canOpenURL:cydiaURL]) return YES;
+    
+    NSArray *paths = @[@"/Applications/Cydia.app",
+                       @"/private/var/lib/apt/",
+                       @"/private/var/lib/cydia",
+                       @"/private/var/stash"];
+    for (NSString *path in paths) {
+        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) return YES;
+    }
+    
+    FILE *bash = fopen("/bin/bash", "r");
+    if (bash != NULL) {
+        fclose(bash);
+        return YES;
+    }
+    
+    NSString *path = [NSString stringWithFormat:@"/private/%@", [NSString stringWithUUID]];
+    if ([@"test" writeToFile : path atomically : YES encoding : NSUTF8StringEncoding error : NULL]) {
+        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
+        return YES;
+    }
+    
+    return NO;
+}
+
+#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
+- (BOOL)canMakePhoneCalls {
+    __block BOOL can;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        can = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel://"]];
+    });
+    return can;
+}
+#endif
+
+- (NSString *)ipAddressWithIfaName:(NSString *)name {
+    if (name.length == 0) return nil;
+    NSString *address = nil;
+    struct ifaddrs *addrs = NULL;
+    if (getifaddrs(&addrs) == 0) {
+        struct ifaddrs *addr = addrs;
+        while (addr) {
+            if ([[NSString stringWithUTF8String:addr->ifa_name] isEqualToString:name]) {
+                sa_family_t family = addr->ifa_addr->sa_family;
+                switch (family) {
+                    case AF_INET: { // IPv4
+                        char str[INET_ADDRSTRLEN] = {0};
+                        inet_ntop(family, &(((struct sockaddr_in *)addr->ifa_addr)->sin_addr), str, sizeof(str));
+                        if (strlen(str) > 0) {
+                            address = [NSString stringWithUTF8String:str];
+                        }
+                    } break;
+                        
+                    case AF_INET6: { // IPv6
+                        char str[INET6_ADDRSTRLEN] = {0};
+                        inet_ntop(family, &(((struct sockaddr_in6 *)addr->ifa_addr)->sin6_addr), str, sizeof(str));
+                        if (strlen(str) > 0) {
+                            address = [NSString stringWithUTF8String:str];
+                        }
+                    }
+                        
+                    default: break;
+                }
+                if (address) break;
+            }
+            addr = addr->ifa_next;
+        }
+    }
+    freeifaddrs(addrs);
+    return address;
+}
+
+- (NSString *)ipAddressWIFI {
+    return [self ipAddressWithIfaName:@"en0"];
+}
+
+- (NSString *)ipAddressCell {
+    return [self ipAddressWithIfaName:@"pdp_ip0"];
+}
+
+
+typedef struct {
+    uint64_t en_in;
+    uint64_t en_out;
+    uint64_t pdp_ip_in;
+    uint64_t pdp_ip_out;
+    uint64_t awdl_in;
+    uint64_t awdl_out;
+} yy_net_interface_counter;
+
+
+static uint64_t yy_net_counter_add(uint64_t counter, uint64_t bytes) {
+    if (bytes < (counter % 0xFFFFFFFF)) {
+        counter += 0xFFFFFFFF - (counter % 0xFFFFFFFF);
+        counter += bytes;
+    } else {
+        counter = bytes;
+    }
+    return counter;
+}
+
+static uint64_t yy_net_counter_get_by_type(yy_net_interface_counter *counter, YYNetworkTrafficType type) {
+    uint64_t bytes = 0;
+    if (type & YYNetworkTrafficTypeWWANSent) bytes += counter->pdp_ip_out;
+    if (type & YYNetworkTrafficTypeWWANReceived) bytes += counter->pdp_ip_in;
+    if (type & YYNetworkTrafficTypeWIFISent) bytes += counter->en_out;
+    if (type & YYNetworkTrafficTypeWIFIReceived) bytes += counter->en_in;
+    if (type & YYNetworkTrafficTypeAWDLSent) bytes += counter->awdl_out;
+    if (type & YYNetworkTrafficTypeAWDLReceived) bytes += counter->awdl_in;
+    return bytes;
+}
+
+static yy_net_interface_counter yy_get_net_interface_counter() {
+    static dispatch_semaphore_t lock;
+    static NSMutableDictionary *sharedInCounters;
+    static NSMutableDictionary *sharedOutCounters;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        sharedInCounters = [NSMutableDictionary new];
+        sharedOutCounters = [NSMutableDictionary new];
+        lock = dispatch_semaphore_create(1);
+    });
+    
+    yy_net_interface_counter counter = {0};
+    struct ifaddrs *addrs;
+    const struct ifaddrs *cursor;
+    if (getifaddrs(&addrs) == 0) {
+        cursor = addrs;
+        dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
+        while (cursor) {
+            if (cursor->ifa_addr->sa_family == AF_LINK) {
+                const struct if_data *data = cursor->ifa_data;
+                NSString *name = cursor->ifa_name ? [NSString stringWithUTF8String:cursor->ifa_name] : nil;
+                if (name) {
+                    uint64_t counter_in = ((NSNumber *)sharedInCounters[name]).unsignedLongLongValue;
+                    counter_in = yy_net_counter_add(counter_in, data->ifi_ibytes);
+                    sharedInCounters[name] = @(counter_in);
+                    
+                    uint64_t counter_out = ((NSNumber *)sharedOutCounters[name]).unsignedLongLongValue;
+                    counter_out = yy_net_counter_add(counter_out, data->ifi_obytes);
+                    sharedOutCounters[name] = @(counter_out);
+                    
+                    if ([name hasPrefix:@"en"]) {
+                        counter.en_in += counter_in;
+                        counter.en_out += counter_out;
+                    } else if ([name hasPrefix:@"awdl"]) {
+                        counter.awdl_in += counter_in;
+                        counter.awdl_out += counter_out;
+                    } else if ([name hasPrefix:@"pdp_ip"]) {
+                        counter.pdp_ip_in += counter_in;
+                        counter.pdp_ip_out += counter_out;
+                    }
+                }
+            }
+            cursor = cursor->ifa_next;
+        }
+        dispatch_semaphore_signal(lock);
+        freeifaddrs(addrs);
+    }
+    
+    return counter;
+}
+
+- (uint64_t)getNetworkTrafficBytes:(YYNetworkTrafficType)types {
+    yy_net_interface_counter counter = yy_get_net_interface_counter();
+    return yy_net_counter_get_by_type(&counter, types);
+}
+
+- (NSString *)machineModel {
+    static dispatch_once_t one;
+    static NSString *model;
+    dispatch_once(&one, ^{
+        size_t size;
+        sysctlbyname("hw.machine", NULL, &size, NULL, 0);
+        char *machine = malloc(size);
+        sysctlbyname("hw.machine", machine, &size, NULL, 0);
+        model = [NSString stringWithUTF8String:machine];
+        free(machine);
+    });
+    return model;
+}
+
+- (NSString *)machineModelName {
+    static dispatch_once_t one;
+    static NSString *name;
+    dispatch_once(&one, ^{
+        NSString *model = [self machineModel];
+        if (!model) return;
+        NSDictionary *dic = @{
+            @"Watch1,1" : @"Apple Watch 38mm",
+            @"Watch1,2" : @"Apple Watch 42mm",
+            @"Watch2,3" : @"Apple Watch Series 2 38mm",
+            @"Watch2,4" : @"Apple Watch Series 2 42mm",
+            @"Watch2,6" : @"Apple Watch Series 1 38mm",
+            @"Watch1,7" : @"Apple Watch Series 1 42mm",
+            
+            @"iPod1,1" : @"iPod touch 1",
+            @"iPod2,1" : @"iPod touch 2",
+            @"iPod3,1" : @"iPod touch 3",
+            @"iPod4,1" : @"iPod touch 4",
+            @"iPod5,1" : @"iPod touch 5",
+            @"iPod7,1" : @"iPod touch 6",
+            
+            @"iPhone1,1" : @"iPhone 1G",
+            @"iPhone1,2" : @"iPhone 3G",
+            @"iPhone2,1" : @"iPhone 3GS",
+            @"iPhone3,1" : @"iPhone 4 (GSM)",
+            @"iPhone3,2" : @"iPhone 4",
+            @"iPhone3,3" : @"iPhone 4 (CDMA)",
+            @"iPhone4,1" : @"iPhone 4S",
+            @"iPhone5,1" : @"iPhone 5",
+            @"iPhone5,2" : @"iPhone 5",
+            @"iPhone5,3" : @"iPhone 5c",
+            @"iPhone5,4" : @"iPhone 5c",
+            @"iPhone6,1" : @"iPhone 5s",
+            @"iPhone6,2" : @"iPhone 5s",
+            @"iPhone7,1" : @"iPhone 6 Plus",
+            @"iPhone7,2" : @"iPhone 6",
+            @"iPhone8,1" : @"iPhone 6s",
+            @"iPhone8,2" : @"iPhone 6s Plus",
+            @"iPhone8,4" : @"iPhone SE",
+            @"iPhone9,1" : @"iPhone 7",
+            @"iPhone9,2" : @"iPhone 7 Plus",
+            @"iPhone9,3" : @"iPhone 7",
+            @"iPhone9,4" : @"iPhone 7 Plus",
+            
+            @"iPad1,1" : @"iPad 1",
+            @"iPad2,1" : @"iPad 2 (WiFi)",
+            @"iPad2,2" : @"iPad 2 (GSM)",
+            @"iPad2,3" : @"iPad 2 (CDMA)",
+            @"iPad2,4" : @"iPad 2",
+            @"iPad2,5" : @"iPad mini 1",
+            @"iPad2,6" : @"iPad mini 1",
+            @"iPad2,7" : @"iPad mini 1",
+            @"iPad3,1" : @"iPad 3 (WiFi)",
+            @"iPad3,2" : @"iPad 3 (4G)",
+            @"iPad3,3" : @"iPad 3 (4G)",
+            @"iPad3,4" : @"iPad 4",
+            @"iPad3,5" : @"iPad 4",
+            @"iPad3,6" : @"iPad 4",
+            @"iPad4,1" : @"iPad Air",
+            @"iPad4,2" : @"iPad Air",
+            @"iPad4,3" : @"iPad Air",
+            @"iPad4,4" : @"iPad mini 2",
+            @"iPad4,5" : @"iPad mini 2",
+            @"iPad4,6" : @"iPad mini 2",
+            @"iPad4,7" : @"iPad mini 3",
+            @"iPad4,8" : @"iPad mini 3",
+            @"iPad4,9" : @"iPad mini 3",
+            @"iPad5,1" : @"iPad mini 4",
+            @"iPad5,2" : @"iPad mini 4",
+            @"iPad5,3" : @"iPad Air 2",
+            @"iPad5,4" : @"iPad Air 2",
+            @"iPad6,3" : @"iPad Pro (9.7 inch)",
+            @"iPad6,4" : @"iPad Pro (9.7 inch)",
+            @"iPad6,7" : @"iPad Pro (12.9 inch)",
+            @"iPad6,8" : @"iPad Pro (12.9 inch)",
+            
+            @"AppleTV2,1" : @"Apple TV 2",
+            @"AppleTV3,1" : @"Apple TV 3",
+            @"AppleTV3,2" : @"Apple TV 3",
+            @"AppleTV5,3" : @"Apple TV 4",
+            
+            @"i386" : @"Simulator x86",
+            @"x86_64" : @"Simulator x64",
+        };
+        name = dic[model];
+        if (!name) name = model;
+    });
+    return name;
+}
+
+- (NSDate *)systemUptime {
+    NSTimeInterval time = [[NSProcessInfo processInfo] systemUptime];
+    return [[NSDate alloc] initWithTimeIntervalSinceNow:(0 - time)];
+}
+
+- (int64_t)diskSpace {
+    NSError *error = nil;
+    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
+    if (error) return -1;
+    int64_t space =  [[attrs objectForKey:NSFileSystemSize] longLongValue];
+    if (space < 0) space = -1;
+    return space;
+}
+
+- (int64_t)diskSpaceFree {
+    NSError *error = nil;
+    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
+    if (error) return -1;
+    int64_t space =  [[attrs objectForKey:NSFileSystemFreeSize] longLongValue];
+    if (space < 0) space = -1;
+    return space;
+}
+
+- (int64_t)diskSpaceUsed {
+    int64_t total = self.diskSpace;
+    int64_t free = self.diskSpaceFree;
+    if (total < 0 || free < 0) return -1;
+    int64_t used = total - free;
+    if (used < 0) used = -1;
+    return used;
+}
+
+- (int64_t)memoryTotal {
+    int64_t mem = [[NSProcessInfo processInfo] physicalMemory];
+    if (mem < -1) mem = -1;
+    return mem;
+}
+
+- (int64_t)memoryUsed {
+    mach_port_t host_port = mach_host_self();
+    mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
+    vm_size_t page_size;
+    vm_statistics_data_t vm_stat;
+    kern_return_t kern;
+    
+    kern = host_page_size(host_port, &page_size);
+    if (kern != KERN_SUCCESS) return -1;
+    kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
+    if (kern != KERN_SUCCESS) return -1;
+    return page_size * (vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count);
+}
+
+- (int64_t)memoryFree {
+    mach_port_t host_port = mach_host_self();
+    mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
+    vm_size_t page_size;
+    vm_statistics_data_t vm_stat;
+    kern_return_t kern;
+    
+    kern = host_page_size(host_port, &page_size);
+    if (kern != KERN_SUCCESS) return -1;
+    kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
+    if (kern != KERN_SUCCESS) return -1;
+    return vm_stat.free_count * page_size;
+}
+
+- (int64_t)memoryActive {
+    mach_port_t host_port = mach_host_self();
+    mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
+    vm_size_t page_size;
+    vm_statistics_data_t vm_stat;
+    kern_return_t kern;
+    
+    kern = host_page_size(host_port, &page_size);
+    if (kern != KERN_SUCCESS) return -1;
+    kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
+    if (kern != KERN_SUCCESS) return -1;
+    return vm_stat.active_count * page_size;
+}
+
+- (int64_t)memoryInactive {
+    mach_port_t host_port = mach_host_self();
+    mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
+    vm_size_t page_size;
+    vm_statistics_data_t vm_stat;
+    kern_return_t kern;
+    
+    kern = host_page_size(host_port, &page_size);
+    if (kern != KERN_SUCCESS) return -1;
+    kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
+    if (kern != KERN_SUCCESS) return -1;
+    return vm_stat.inactive_count * page_size;
+}
+
+- (int64_t)memoryWired {
+    mach_port_t host_port = mach_host_self();
+    mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
+    vm_size_t page_size;
+    vm_statistics_data_t vm_stat;
+    kern_return_t kern;
+    
+    kern = host_page_size(host_port, &page_size);
+    if (kern != KERN_SUCCESS) return -1;
+    kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
+    if (kern != KERN_SUCCESS) return -1;
+    return vm_stat.wire_count * page_size;
+}
+
+- (int64_t)memoryPurgable {
+    mach_port_t host_port = mach_host_self();
+    mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
+    vm_size_t page_size;
+    vm_statistics_data_t vm_stat;
+    kern_return_t kern;
+    
+    kern = host_page_size(host_port, &page_size);
+    if (kern != KERN_SUCCESS) return -1;
+    kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
+    if (kern != KERN_SUCCESS) return -1;
+    return vm_stat.purgeable_count * page_size;
+}
+
+- (NSUInteger)cpuCount {
+    return [NSProcessInfo processInfo].activeProcessorCount;
+}
+
+- (float)cpuUsage {
+    float cpu = 0;
+    NSArray *cpus = [self cpuUsagePerProcessor];
+    if (cpus.count == 0) return -1;
+    for (NSNumber *n in cpus) {
+        cpu += n.floatValue;
+    }
+    return cpu;
+}
+
+- (NSArray *)cpuUsagePerProcessor {
+    processor_info_array_t _cpuInfo, _prevCPUInfo = nil;
+    mach_msg_type_number_t _numCPUInfo, _numPrevCPUInfo = 0;
+    unsigned _numCPUs;
+    NSLock *_cpuUsageLock;
+    
+    int _mib[2U] = { CTL_HW, HW_NCPU };
+    size_t _sizeOfNumCPUs = sizeof(_numCPUs);
+    int _status = sysctl(_mib, 2U, &_numCPUs, &_sizeOfNumCPUs, NULL, 0U);
+    if (_status)
+        _numCPUs = 1;
+    
+    _cpuUsageLock = [[NSLock alloc] init];
+    
+    natural_t _numCPUsU = 0U;
+    kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &_numCPUsU, &_cpuInfo, &_numCPUInfo);
+    if (err == KERN_SUCCESS) {
+        [_cpuUsageLock lock];
+        
+        NSMutableArray *cpus = [NSMutableArray new];
+        for (unsigned i = 0U; i < _numCPUs; ++i) {
+            Float32 _inUse, _total;
+            if (_prevCPUInfo) {
+                _inUse = (
+                          (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER]   - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
+                          + (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
+                          + (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]   - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE])
+                          );
+                _total = _inUse + (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
+            } else {
+                _inUse = _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
+                _total = _inUse + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
+            }
+            [cpus addObject:@(_inUse / _total)];
+        }
+        
+        [_cpuUsageLock unlock];
+        if (_prevCPUInfo) {
+            size_t prevCpuInfoSize = sizeof(integer_t) * _numPrevCPUInfo;
+            vm_deallocate(mach_task_self(), (vm_address_t)_prevCPUInfo, prevCpuInfoSize);
+        }
+        return cpus;
+    } else {
+        return nil;
+    }
+}
+
+@end

+ 153 - 0
YYKit/Base/UIKit/UIFont+YYAdd.h

@@ -0,0 +1,153 @@
+//
+//  UIFont+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+#import <CoreGraphics/CoreGraphics.h>
+#import <CoreText/CoreText.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIFont`.
+ */
+@interface UIFont (YYAdd) <NSCoding>
+
+#pragma mark - Font Traits
+///=============================================================================
+/// @name Font Traits
+///=============================================================================
+
+@property (nonatomic, readonly) BOOL isBold NS_AVAILABLE_IOS(7_0); ///< Whether the font is bold.
+@property (nonatomic, readonly) BOOL isItalic NS_AVAILABLE_IOS(7_0); ///< Whether the font is italic.
+@property (nonatomic, readonly) BOOL isMonoSpace NS_AVAILABLE_IOS(7_0); ///< Whether the font is mono space.
+@property (nonatomic, readonly) BOOL isColorGlyphs NS_AVAILABLE_IOS(7_0); ///< Whether the font is color glyphs (such as Emoji).
+@property (nonatomic, readonly) CGFloat fontWeight NS_AVAILABLE_IOS(7_0); ///< Font weight from -1.0 to 1.0. Regular weight is 0.0.
+
+/**
+ Create a bold font from receiver.
+ @return A bold font, or nil if failed.
+ */
+- (nullable UIFont *)fontWithBold NS_AVAILABLE_IOS(7_0);
+
+/**
+ Create a italic font from receiver.
+ @return A italic font, or nil if failed.
+ */
+- (nullable UIFont *)fontWithItalic NS_AVAILABLE_IOS(7_0);
+
+/**
+ Create a bold and italic font from receiver.
+ @return A bold and italic font, or nil if failed.
+ */
+- (nullable UIFont *)fontWithBoldItalic NS_AVAILABLE_IOS(7_0);
+
+/**
+ Create a normal (no bold/italic/...) font from receiver.
+ @return A normal font, or nil if failed.
+ */
+- (nullable UIFont *)fontWithNormal NS_AVAILABLE_IOS(7_0);
+
+#pragma mark - Create font
+///=============================================================================
+/// @name Create font
+///=============================================================================
+
+/**
+ Creates and returns a font object for the specified CTFontRef.
+ 
+ @param CTFont  CoreText font.
+ */
++ (nullable UIFont *)fontWithCTFont:(CTFontRef)CTFont;
+
+/**
+ Creates and returns a font object for the specified CGFontRef and size.
+ 
+ @param CGFont  CoreGraphic font.
+ @param size    Font size.
+ */
++ (nullable UIFont *)fontWithCGFont:(CGFontRef)CGFont size:(CGFloat)size;
+
+/**
+ Creates and returns the CTFontRef object. (need call CFRelease() after used)
+ */
+- (nullable CTFontRef)CTFontRef CF_RETURNS_RETAINED;
+
+/**
+ Creates and returns the CGFontRef object. (need call CFRelease() after used)
+ */
+- (nullable CGFontRef)CGFontRef CF_RETURNS_RETAINED;
+
+
+#pragma mark - Load and unload font
+///=============================================================================
+/// @name Load and unload font
+///=============================================================================
+
+/**
+ Load the font from file path. Support format:TTF,OTF.
+ If return YES, font can be load use it PostScript Name: [UIFont fontWithName:...]
+ 
+ @param path    font file's full path
+ */
++ (BOOL)loadFontFromPath:(NSString *)path;
+
+/**
+ Unload font from file path.
+ 
+ @param path    font file's full path
+ */
++ (void)unloadFontFromPath:(NSString *)path;
+
+/**
+ Load the font from data. Support format:TTF,OTF.
+ 
+ @param data  Font data.
+ 
+ @return UIFont object if load succeed, otherwise nil.
+ */
++ (nullable UIFont *)loadFontFromData:(NSData *)data;
+
+/**
+ Unload font which is loaded by loadFontFromData: function.
+ 
+ @param font the font loaded by loadFontFromData: function
+ 
+ @return YES if succeed, otherwise NO.
+ */
++ (BOOL)unloadFontFromData:(UIFont *)font;
+
+
+#pragma mark - Dump font data
+///=============================================================================
+/// @name Dump font data
+///=============================================================================
+
+/**
+ Serialize and return the font data.
+ 
+ @param font The font.
+ 
+ @return data in TTF, or nil if an error occurs.
+ */
++ (nullable NSData *)dataFromFont:(UIFont *)font;
+
+/**
+ Serialize and return the font data.
+ 
+ @param cgFont The font.
+ 
+ @return data in TTF, or nil if an error occurs.
+ */
++ (nullable NSData *)dataFromCGFont:(CGFontRef)cgFont;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 269 - 0
YYKit/Base/UIKit/UIFont+YYAdd.m

@@ -0,0 +1,269 @@
+//
+//  UIFont+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIFont+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(UIFont_YYAdd)
+
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wprotocol"
+// Apple has implemented UIFont<NSCoding>, but did not make it public.
+
+@implementation UIFont (YYAdd)
+
+- (BOOL)isBold {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
+    return (self.fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold) > 0;
+}
+
+- (BOOL)isItalic {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
+    return (self.fontDescriptor.symbolicTraits & UIFontDescriptorTraitItalic) > 0;
+}
+
+- (BOOL)isMonoSpace {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
+    return (self.fontDescriptor.symbolicTraits & UIFontDescriptorTraitMonoSpace) > 0;
+}
+
+- (BOOL)isColorGlyphs {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
+    return (CTFontGetSymbolicTraits((__bridge CTFontRef)self) & kCTFontTraitColorGlyphs) != 0;
+}
+
+- (CGFloat)fontWeight {
+    NSDictionary *traits = [self.fontDescriptor objectForKey:UIFontDescriptorTraitsAttribute];
+    return [traits[UIFontWeightTrait] floatValue];
+}
+
+- (UIFont *)fontWithBold {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
+    return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:self.pointSize];
+}
+
+- (UIFont *)fontWithItalic {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
+    return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic] size:self.pointSize];
+}
+
+- (UIFont *)fontWithBoldItalic {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
+    return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic] size:self.pointSize];
+}
+
+- (UIFont *)fontWithNormal {
+    if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
+    return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:0] size:self.pointSize];
+}
+
++ (UIFont *)fontWithCTFont:(CTFontRef)CTFont {
+    if (!CTFont) return nil;
+    CFStringRef name = CTFontCopyPostScriptName(CTFont);
+    if (!name) return nil;
+    CGFloat size = CTFontGetSize(CTFont);
+    UIFont *font = [self fontWithName:(__bridge NSString *)(name) size:size];
+    CFRelease(name);
+    return font;
+}
+
++ (UIFont *)fontWithCGFont:(CGFontRef)CGFont size:(CGFloat)size {
+    if (!CGFont) return nil;
+    CFStringRef name = CGFontCopyPostScriptName(CGFont);
+    if (!name) return nil;
+    UIFont *font = [self fontWithName:(__bridge NSString *)(name) size:size];
+    CFRelease(name);
+    return font;
+}
+
+- (CTFontRef)CTFontRef CF_RETURNS_RETAINED {
+    CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.fontName, self.pointSize, NULL);
+    return font;
+}
+
+- (CGFontRef)CGFontRef CF_RETURNS_RETAINED {
+    CGFontRef font = CGFontCreateWithFontName((__bridge CFStringRef)self.fontName);
+    return font;
+}
+
++ (BOOL)loadFontFromPath:(NSString *)path {
+    NSURL *url = [NSURL fileURLWithPath:path];
+    CFErrorRef error;
+    BOOL suc = CTFontManagerRegisterFontsForURL((__bridge CFTypeRef)url, kCTFontManagerScopeNone, &error);
+    if (!suc) {
+        NSLog(@"Failed to load font: %@", error);
+    }
+    return suc;
+}
+
++ (void)unloadFontFromPath:(NSString *)path {
+    NSURL *url = [NSURL fileURLWithPath:path];
+    CTFontManagerUnregisterFontsForURL((__bridge CFTypeRef)url, kCTFontManagerScopeNone, NULL);
+}
+
++ (UIFont *)loadFontFromData:(NSData *)data {
+    CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
+    if (!provider) return nil;
+    CGFontRef fontRef = CGFontCreateWithDataProvider(provider);
+    CGDataProviderRelease(provider);
+    if (!fontRef) return nil;
+    
+    CFErrorRef errorRef;
+    BOOL suc = CTFontManagerRegisterGraphicsFont(fontRef, &errorRef);
+    if (!suc) {
+        CFRelease(fontRef);
+        NSLog(@"%@", errorRef);
+        return nil;
+    } else {
+        CFStringRef fontName = CGFontCopyPostScriptName(fontRef);
+        UIFont *font = [UIFont fontWithName:(__bridge NSString *)(fontName) size:[UIFont systemFontSize]];
+        if (fontName) CFRelease(fontName);
+        CGFontRelease(fontRef);
+        return font;
+    }
+}
+
++ (BOOL)unloadFontFromData:(UIFont *)font {
+    CGFontRef fontRef = CGFontCreateWithFontName((__bridge CFStringRef)font.fontName);
+    if (!fontRef) return NO;
+    CFErrorRef errorRef;
+    BOOL suc = CTFontManagerUnregisterGraphicsFont(fontRef, &errorRef);
+    CFRelease(fontRef);
+    if (!suc) NSLog(@"%@", errorRef);
+    return suc;
+}
+
++ (NSData *)dataFromFont:(UIFont *)font {
+    CGFontRef cgFont = font.CGFontRef;
+    NSData *data = [self dataFromCGFont:cgFont];
+    CGFontRelease(cgFont);
+    return data;
+}
+
+typedef struct FontHeader {
+    int32_t fVersion;
+    uint16_t fNumTables;
+    uint16_t fSearchRange;
+    uint16_t fEntrySelector;
+    uint16_t fRangeShift;
+} FontHeader;
+
+typedef struct TableEntry {
+    uint32_t fTag;
+    uint32_t fCheckSum;
+    uint32_t fOffset;
+    uint32_t fLength;
+} TableEntry;
+
+static uint32_t CalcTableCheckSum(const uint32_t *table, uint32_t numberOfBytesInTable) {
+    uint32_t sum = 0;
+    uint32_t nLongs = (numberOfBytesInTable + 3) / 4;
+    while (nLongs-- > 0) {
+        sum += CFSwapInt32HostToBig(*table++);
+    }
+    return sum;
+}
+
+//Reference:
+//https://github.com/google/skia/blob/master/src%2Fports%2FSkFontHost_mac.cpp
++ (NSData *)dataFromCGFont:(CGFontRef)cgFont {
+    if (!cgFont) return nil;
+    
+    CFRetain(cgFont);
+    
+    CFArrayRef tags = CGFontCopyTableTags(cgFont);
+    if (!tags) return nil;
+    CFIndex tableCount = CFArrayGetCount(tags);
+    
+    size_t *tableSizes = malloc(sizeof(size_t) * tableCount);
+    memset(tableSizes, 0, sizeof(size_t) * tableCount);
+    
+    BOOL containsCFFTable = NO;
+    
+    size_t totalSize = sizeof(FontHeader) + sizeof(TableEntry) * tableCount;
+    
+    for (CFIndex index = 0; index < tableCount; index++) {
+        size_t tableSize = 0;
+        uint32_t aTag = (uint32_t)CFArrayGetValueAtIndex(tags, index);
+        if (aTag == kCTFontTableCFF && !containsCFFTable) {
+            containsCFFTable = YES;
+        }
+        CFDataRef tableDataRef = CGFontCopyTableForTag(cgFont, aTag);
+        if (tableDataRef) {
+            tableSize = CFDataGetLength(tableDataRef);
+            CFRelease(tableDataRef);
+        }
+        totalSize += (tableSize + 3) & ~3;
+        tableSizes[index] = tableSize;
+    }
+    
+    unsigned char *stream = malloc(totalSize);
+    memset(stream, 0, totalSize);
+    char *dataStart = (char *)stream;
+    char *dataPtr = dataStart;
+    
+    // compute font header entries
+    uint16_t entrySelector = 0;
+    uint16_t searchRange = 1;
+    while (searchRange < tableCount >> 1) {
+        entrySelector++;
+        searchRange <<= 1;
+    }
+    searchRange <<= 4;
+    
+    uint16_t rangeShift = (tableCount << 4) - searchRange;
+    
+    // write font header (also called sfnt header, offset subtable)
+    FontHeader *offsetTable = (FontHeader *)dataPtr;
+    
+    //OpenType Font contains CFF Table use 'OTTO' as version, and with .otf extension
+    //otherwise 0001 0000
+    offsetTable->fVersion = containsCFFTable ? 'OTTO' : CFSwapInt16HostToBig(1);
+    offsetTable->fNumTables = CFSwapInt16HostToBig((uint16_t)tableCount);
+    offsetTable->fSearchRange = CFSwapInt16HostToBig((uint16_t)searchRange);
+    offsetTable->fEntrySelector = CFSwapInt16HostToBig((uint16_t)entrySelector);
+    offsetTable->fRangeShift = CFSwapInt16HostToBig((uint16_t)rangeShift);
+    
+    dataPtr += sizeof(FontHeader);
+    
+    // write tables
+    TableEntry *entry = (TableEntry *)dataPtr;
+    dataPtr += sizeof(TableEntry) * tableCount;
+    
+    for (int index = 0; index < tableCount; ++index) {
+        uint32_t aTag = (uint32_t)CFArrayGetValueAtIndex(tags, index);
+        CFDataRef tableDataRef = CGFontCopyTableForTag(cgFont, aTag);
+        size_t tableSize = CFDataGetLength(tableDataRef);
+        
+        memcpy(dataPtr, CFDataGetBytePtr(tableDataRef), tableSize);
+        
+        entry->fTag = CFSwapInt32HostToBig((uint32_t)aTag);
+        entry->fCheckSum = CFSwapInt32HostToBig(CalcTableCheckSum((uint32_t *)dataPtr, (uint32_t)tableSize));
+        
+        uint32_t offset = (uint32_t)dataPtr - (uint32_t)dataStart;
+        entry->fOffset = CFSwapInt32HostToBig((uint32_t)offset);
+        entry->fLength = CFSwapInt32HostToBig((uint32_t)tableSize);
+        dataPtr += (tableSize + 3) & ~3;
+        ++entry;
+        CFRelease(tableDataRef);
+    }
+    
+    CFRelease(cgFont);
+    CFRelease(tags);
+    free(tableSizes);
+    NSData *fontData = [NSData dataWithBytesNoCopy:stream length:totalSize freeWhenDone:YES];
+    return fontData;
+}
+
+@end
+
+#pragma clang diagnostic pop

+ 47 - 0
YYKit/Base/UIKit/UIGestureRecognizer+YYAdd.h

@@ -0,0 +1,47 @@
+//
+//  UIGestureRecognizer+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/10/13.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIGestureRecognizer`.
+ */
+@interface UIGestureRecognizer (YYAdd)
+
+/**
+ Initializes an allocated gesture-recognizer object with a action block.
+ 
+ @param block  An action block that to handle the gesture recognized by the 
+               receiver. nil is invalid. It is retained by the gesture.
+ 
+ @return An initialized instance of a concrete UIGestureRecognizer subclass or 
+         nil if an error occurred in the attempt to initialize the object.
+ */
+- (instancetype)initWithActionBlock:(void (^)(id sender))block;
+
+/**
+ Adds an action block to a gesture-recognizer object. It is retained by the 
+ gesture.
+ 
+ @param block A block invoked by the action message. nil is not a valid value.
+ */
+- (void)addActionBlock:(void (^)(id sender))block;
+
+/**
+ Remove all action blocks.
+ */
+- (void)removeAllActionBlocks;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 78 - 0
YYKit/Base/UIKit/UIGestureRecognizer+YYAdd.m

@@ -0,0 +1,78 @@
+//
+//  UIGestureRecognizer+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/10/13.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIGestureRecognizer+YYAdd.h"
+#import "YYKitMacro.h"
+#import <objc/runtime.h>
+
+static const int block_key;
+
+@interface _YYUIGestureRecognizerBlockTarget : NSObject
+
+@property (nonatomic, copy) void (^block)(id sender);
+
+- (id)initWithBlock:(void (^)(id sender))block;
+- (void)invoke:(id)sender;
+
+@end
+
+@implementation _YYUIGestureRecognizerBlockTarget
+
+- (id)initWithBlock:(void (^)(id sender))block{
+    self = [super init];
+    if (self) {
+        _block = [block copy];
+    }
+    return self;
+}
+
+- (void)invoke:(id)sender {
+    if (_block) _block(sender);
+}
+
+@end
+
+
+
+
+@implementation UIGestureRecognizer (YYAdd)
+
+- (instancetype)initWithActionBlock:(void (^)(id sender))block {
+    self = [self init];
+    [self addActionBlock:block];
+    return self;
+}
+
+- (void)addActionBlock:(void (^)(id sender))block {
+    _YYUIGestureRecognizerBlockTarget *target = [[_YYUIGestureRecognizerBlockTarget alloc] initWithBlock:block];
+    [self addTarget:target action:@selector(invoke:)];
+    NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
+    [targets addObject:target];
+}
+
+- (void)removeAllActionBlocks{
+    NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
+    [targets enumerateObjectsUsingBlock:^(id target, NSUInteger idx, BOOL *stop) {
+        [self removeTarget:target action:@selector(invoke:)];
+    }];
+    [targets removeAllObjects];
+}
+
+- (NSMutableArray *)_yy_allUIGestureRecognizerBlockTargets {
+    NSMutableArray *targets = objc_getAssociatedObject(self, &block_key);
+    if (!targets) {
+        targets = [NSMutableArray array];
+        objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return targets;
+}
+
+@end

+ 377 - 0
YYKit/Base/UIKit/UIImage+YYAdd.h

@@ -0,0 +1,377 @@
+//
+//  UIImage+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provide some commen method for `UIImage`.
+ Image process is based on CoreGraphic and vImage.
+ */
+@interface UIImage (YYAdd)
+
+#pragma mark - Create image
+///=============================================================================
+/// @name Create image
+///=============================================================================
+
+/**
+ Create an animated image with GIF data. After created, you can access
+ the images via property '.images'. If the data is not animated gif, this
+ function is same as [UIImage imageWithData:data scale:scale];
+ 
+ @discussion     It has a better display performance, but costs more memory
+                 (width * height * frames Bytes). It only suited to display small 
+                 gif such as animated emoticon. If you want to display large gif, 
+                 see `YYImage`.
+ 
+ @param data     GIF data.
+ 
+ @param scale    The scale factor
+ 
+ @return A new image created from GIF, or nil when an error occurs.
+ */
++ (nullable UIImage *)imageWithSmallGIFData:(NSData *)data scale:(CGFloat)scale;
+
+/**
+ Whether the data is animated GIF.
+ 
+ @param data Image data
+ 
+ @return Returns YES only if the data is gif and contains more than one frame,
+         otherwise returns NO.
+ */
++ (BOOL)isAnimatedGIFData:(NSData *)data;
+
+/**
+ Whether the file in the specified path is GIF.
+ 
+ @param path An absolute file path.
+ 
+ @return Returns YES if the file is gif, otherwise returns NO.
+ */
++ (BOOL)isAnimatedGIFFile:(NSString *)path;
+
+/**
+ Create an image from a PDF file data or path.
+ 
+ @discussion If the PDF has multiple page, is just return's the first page's
+ content. Image's scale is equal to current screen's scale, size is same as 
+ PDF's origin size.
+ 
+ @param dataOrPath PDF data in `NSData`, or PDF file path in `NSString`.
+ 
+ @return A new image create from PDF, or nil when an error occurs.
+ */
++ (nullable UIImage *)imageWithPDF:(id)dataOrPath;
+
+/**
+ Create an image from a PDF file data or path.
+ 
+ @discussion If the PDF has multiple page, is just return's the first page's
+ content. Image's scale is equal to current screen's scale.
+ 
+ @param dataOrPath  PDF data in `NSData`, or PDF file path in `NSString`.
+ 
+ @param size     The new image's size, PDF's content will be stretched as needed.
+ 
+ @return A new image create from PDF, or nil when an error occurs.
+ */
++ (nullable UIImage *)imageWithPDF:(id)dataOrPath size:(CGSize)size;
+
+/**
+ Create a square image from apple emoji.
+ 
+ @discussion It creates a square image from apple emoji, image's scale is equal
+ to current screen's scale. The original emoji image in `AppleColorEmoji` font 
+ is in size 160*160 px.
+ 
+ @param emoji single emoji, such as @"😄".
+ 
+ @param size  image's size.
+ 
+ @return Image from emoji, or nil when an error occurs.
+ */
++ (nullable UIImage *)imageWithEmoji:(NSString *)emoji size:(CGFloat)size;
+
+/**
+ Create and return a 1x1 point size image with the given color.
+ 
+ @param color  The color.
+ */
++ (nullable UIImage *)imageWithColor:(UIColor *)color;
+
+/**
+ Create and return a pure color image with the given color and size.
+ 
+ @param color  The color.
+ @param size   New image's type.
+ */
++ (nullable UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size;
+
+/**
+ Create and return an image with custom draw code.
+ 
+ @param size      The image size.
+ @param drawBlock The draw block.
+ 
+ @return The new image.
+ */
++ (nullable UIImage *)imageWithSize:(CGSize)size drawBlock:(void (^)(CGContextRef context))drawBlock;
+
+#pragma mark - Image Info
+///=============================================================================
+/// @name Image Info
+///=============================================================================
+
+/**
+ Whether this image has alpha channel.
+ */
+- (BOOL)hasAlphaChannel;
+
+
+#pragma mark - Modify Image
+///=============================================================================
+/// @name Modify Image
+///=============================================================================
+
+/**
+ Draws the entire image in the specified rectangle, content changed with
+ the contentMode.
+ 
+ @discussion This method draws the entire image in the current graphics context, 
+ respecting the image's orientation setting. In the default coordinate system, 
+ images are situated down and to the right of the origin of the specified 
+ rectangle. This method respects any transforms applied to the current graphics 
+ context, however.
+ 
+ @param rect        The rectangle in which to draw the image.
+ 
+ @param contentMode Draw content mode
+ 
+ @param clips       A Boolean value that determines whether content are confined to the rect.
+ */
+- (void)drawInRect:(CGRect)rect withContentMode:(UIViewContentMode)contentMode clipsToBounds:(BOOL)clips;
+
+/**
+ Returns a new image which is scaled from this image.
+ The image will be stretched as needed.
+ 
+ @param size  The new size to be scaled, values should be positive.
+ 
+ @return      The new image with the given size.
+ */
+- (nullable UIImage *)imageByResizeToSize:(CGSize)size;
+
+/**
+ Returns a new image which is scaled from this image.
+ The image content will be changed with thencontentMode.
+ 
+ @param size        The new size to be scaled, values should be positive.
+ 
+ @param contentMode The content mode for image content.
+ 
+ @return The new image with the given size.
+ */
+- (nullable UIImage *)imageByResizeToSize:(CGSize)size contentMode:(UIViewContentMode)contentMode;
+
+/**
+ Returns a new image which is cropped from this image.
+ 
+ @param rect  Image's inner rect.
+ 
+ @return      The new image, or nil if an error occurs.
+ */
+- (nullable UIImage *)imageByCropToRect:(CGRect)rect;
+
+/**
+ Returns a new image which is edge inset from this image.
+ 
+ @param insets  Inset (positive) for each of the edges, values can be negative to 'outset'.
+ 
+ @param color   Extend edge's fill color, nil means clear color.
+ 
+ @return        The new image, or nil if an error occurs.
+ */
+- (nullable UIImage *)imageByInsetEdge:(UIEdgeInsets)insets withColor:(nullable UIColor *)color;
+
+/**
+ Rounds a new image with a given corner size.
+ 
+ @param radius  The radius of each corner oval. Values larger than half the
+                rectangle's width or height are clamped appropriately to half
+                the width or height.
+ */
+- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius;
+
+/**
+ Rounds a new image with a given corner size.
+ 
+ @param radius       The radius of each corner oval. Values larger than half the
+                     rectangle's width or height are clamped appropriately to
+                     half the width or height.
+
+ @param borderWidth  The inset border line width. Values larger than half the rectangle's
+                     width or height are clamped appropriately to half the width 
+                     or height.
+ 
+ @param borderColor  The border stroke color. nil means clear color.
+ */
+- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius
+                                   borderWidth:(CGFloat)borderWidth
+                                   borderColor:(nullable UIColor *)borderColor;
+
+/**
+ Rounds a new image with a given corner size.
+ 
+ @param radius       The radius of each corner oval. Values larger than half the
+                     rectangle's width or height are clamped appropriately to
+                     half the width or height.
+ 
+ @param corners      A bitmask value that identifies the corners that you want
+                     rounded. You can use this parameter to round only a subset
+                     of the corners of the rectangle.
+ 
+ @param borderWidth  The inset border line width. Values larger than half the rectangle's
+                     width or height are clamped appropriately to half the width 
+                     or height.
+ 
+ @param borderColor  The border stroke color. nil means clear color.
+ 
+ @param borderLineJoin The border line join.
+ */
+- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius
+                                       corners:(UIRectCorner)corners
+                                   borderWidth:(CGFloat)borderWidth
+                                   borderColor:(nullable UIColor *)borderColor
+                                borderLineJoin:(CGLineJoin)borderLineJoin;
+
+/**
+ Returns a new rotated image (relative to the center).
+ 
+ @param radians   Rotated radians in counterclockwise.⟲
+ 
+ @param fitSize   YES: new image's size is extend to fit all content.
+                  NO: image's size will not change, content may be clipped.
+ */
+- (nullable UIImage *)imageByRotate:(CGFloat)radians fitSize:(BOOL)fitSize;
+
+/**
+ Returns a new image rotated counterclockwise by a quarter‑turn (90°). ⤺
+ The width and height will be exchanged.
+ */
+- (nullable UIImage *)imageByRotateLeft90;
+
+/**
+ Returns a new image rotated clockwise by a quarter‑turn (90°). ⤼
+ The width and height will be exchanged.
+ */
+- (nullable UIImage *)imageByRotateRight90;
+
+/**
+ Returns a new image rotated 180° . ↻
+ */
+- (nullable UIImage *)imageByRotate180;
+
+/**
+ Returns a vertically flipped image. ⥯
+ */
+- (nullable UIImage *)imageByFlipVertical;
+
+/**
+ Returns a horizontally flipped image. ⇋
+ */
+- (nullable UIImage *)imageByFlipHorizontal;
+
+
+#pragma mark - Image Effect
+///=============================================================================
+/// @name Image Effect
+///=============================================================================
+
+/**
+ Tint the image in alpha channel with the given color.
+ 
+ @param color  The color.
+ */
+- (nullable UIImage *)imageByTintColor:(UIColor *)color;
+
+/**
+ Returns a grayscaled image.
+ */
+- (nullable UIImage *)imageByGrayscale;
+
+/**
+ Applies a blur effect to this image. Suitable for blur any content.
+ */
+- (nullable UIImage *)imageByBlurSoft;
+
+/**
+ Applies a blur effect to this image. Suitable for blur any content except pure white.
+ (same as iOS Control Panel)
+ */
+- (nullable UIImage *)imageByBlurLight;
+
+/**
+ Applies a blur effect to this image. Suitable for displaying black text.
+ (same as iOS Navigation Bar White)
+ */
+- (nullable UIImage *)imageByBlurExtraLight;
+
+/**
+ Applies a blur effect to this image. Suitable for displaying white text.
+ (same as iOS Notification Center)
+ */
+- (nullable UIImage *)imageByBlurDark;
+
+/**
+ Applies a blur and tint color to this image.
+ 
+ @param tintColor  The tint color.
+ */
+- (nullable UIImage *)imageByBlurWithTint:(UIColor *)tintColor;
+
+/**
+ Applies a blur, tint color, and saturation adjustment to this image,
+ optionally within the area specified by @a maskImage.
+ 
+ @param blurRadius     The radius of the blur in points, 0 means no blur effect.
+ 
+ @param tintColor      An optional UIColor object that is uniformly blended with
+                       the result of the blur and saturation operations. The
+                       alpha channel of this color determines how strong the
+                       tint is. nil means no tint.
+ 
+ @param tintBlendMode  The @a tintColor blend mode. Default is kCGBlendModeNormal (0).
+ 
+ @param saturation     A value of 1.0 produces no change in the resulting image.
+                       Values less than 1.0 will desaturation the resulting image
+                       while values greater than 1.0 will have the opposite effect.
+                       0 means gray scale.
+ 
+ @param maskImage      If specified, @a inputImage is only modified in the area(s)
+                       defined by this mask.  This must be an image mask or it
+                       must meet the requirements of the mask parameter of
+                       CGContextClipToMask.
+ 
+ @return               image with effect, or nil if an error occurs (e.g. no
+                       enough memory).
+ */
+- (nullable UIImage *)imageByBlurRadius:(CGFloat)blurRadius
+                              tintColor:(nullable UIColor *)tintColor
+                               tintMode:(CGBlendMode)tintBlendMode
+                             saturation:(CGFloat)saturation
+                              maskImage:(nullable UIImage *)maskImage;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 752 - 0
YYKit/Base/UIKit/UIImage+YYAdd.m

@@ -0,0 +1,752 @@
+//
+//  UIImage+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/4.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIImage+YYAdd.h"
+#import "UIDevice+YYAdd.h"
+#import "NSString+YYAdd.h"
+#import "YYKitMacro.h"
+#import "YYCGUtilities.h"
+#import <ImageIO/ImageIO.h>
+#import <Accelerate/Accelerate.h>
+#import <CoreText/CoreText.h>
+#import <objc/runtime.h>
+#import "YYCGUtilities.h"
+
+YYSYNTH_DUMMY_CLASS(UIImage_YYAdd)
+
+static NSTimeInterval _yy_CGImageSourceGetGIFFrameDelayAtIndex(CGImageSourceRef source, size_t index) {
+    NSTimeInterval delay = 0;
+    CFDictionaryRef dic = CGImageSourceCopyPropertiesAtIndex(source, index, NULL);
+    if (dic) {
+        CFDictionaryRef dicGIF = CFDictionaryGetValue(dic, kCGImagePropertyGIFDictionary);
+        if (dicGIF) {
+            NSNumber *num = CFDictionaryGetValue(dicGIF, kCGImagePropertyGIFUnclampedDelayTime);
+            if (num.doubleValue <= __FLT_EPSILON__) {
+                num = CFDictionaryGetValue(dicGIF, kCGImagePropertyGIFDelayTime);
+            }
+            delay = num.doubleValue;
+        }
+        CFRelease(dic);
+    }
+    
+    // http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser-compatibility
+    if (delay < 0.02) delay = 0.1;
+    return delay;
+}
+
+
+
+@implementation UIImage (YYAdd)
+
++ (UIImage *)imageWithSmallGIFData:(NSData *)data scale:(CGFloat)scale {
+    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFTypeRef)(data), NULL);
+    if (!source) return nil;
+    
+    size_t count = CGImageSourceGetCount(source);
+    if (count <= 1) {
+        CFRelease(source);
+        return [self.class imageWithData:data scale:scale];
+    }
+    
+    NSUInteger frames[count];
+    double oneFrameTime = 1 / 50.0; // 50 fps
+    NSTimeInterval totalTime = 0;
+    NSUInteger totalFrame = 0;
+    NSUInteger gcdFrame = 0;
+    for (size_t i = 0; i < count; i++) {
+        NSTimeInterval delay = _yy_CGImageSourceGetGIFFrameDelayAtIndex(source, i);
+        totalTime += delay;
+        NSInteger frame = lrint(delay / oneFrameTime);
+        if (frame < 1) frame = 1;
+        frames[i] = frame;
+        totalFrame += frames[i];
+        if (i == 0) gcdFrame = frames[i];
+        else {
+            NSUInteger frame = frames[i], tmp;
+            if (frame < gcdFrame) {
+                tmp = frame; frame = gcdFrame; gcdFrame = tmp;
+            }
+            while (true) {
+                tmp = frame % gcdFrame;
+                if (tmp == 0) break;
+                frame = gcdFrame;
+                gcdFrame = tmp;
+            }
+        }
+    }
+    NSMutableArray *array = [NSMutableArray new];
+    for (size_t i = 0; i < count; i++) {
+        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
+        if (!imageRef) {
+            CFRelease(source);
+            return nil;
+        }
+        size_t width = CGImageGetWidth(imageRef);
+        size_t height = CGImageGetHeight(imageRef);
+        if (width == 0 || height == 0) {
+            CFRelease(source);
+            CFRelease(imageRef);
+            return nil;
+        }
+        
+        CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef) & kCGBitmapAlphaInfoMask;
+        BOOL hasAlpha = NO;
+        if (alphaInfo == kCGImageAlphaPremultipliedLast ||
+            alphaInfo == kCGImageAlphaPremultipliedFirst ||
+            alphaInfo == kCGImageAlphaLast ||
+            alphaInfo == kCGImageAlphaFirst) {
+            hasAlpha = YES;
+        }
+        // BGRA8888 (premultiplied) or BGRX8888
+        // same as UIGraphicsBeginImageContext() and -[UIView drawRect:]
+        CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host;
+        bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst;
+        CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
+        CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, bitmapInfo);
+        CGColorSpaceRelease(space);
+        if (!context) {
+            CFRelease(source);
+            CFRelease(imageRef);
+            return nil;
+        }
+        CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); // decode
+        CGImageRef decoded = CGBitmapContextCreateImage(context);
+        CFRelease(context);
+        if (!decoded) {
+            CFRelease(source);
+            CFRelease(imageRef);
+            return nil;
+        }
+        UIImage *image = [UIImage imageWithCGImage:decoded scale:scale orientation:UIImageOrientationUp];
+        CGImageRelease(imageRef);
+        CGImageRelease(decoded);
+        if (!image) {
+            CFRelease(source);
+            return nil;
+        }
+        for (size_t j = 0, max = frames[i] / gcdFrame; j < max; j++) {
+            [array addObject:image];
+        }
+    }
+    CFRelease(source);
+    UIImage *image = [self.class animatedImageWithImages:array duration:totalTime];
+    return image;
+}
+
++ (BOOL)isAnimatedGIFData:(NSData *)data {
+    if (data.length < 16) return NO;
+    UInt32 magic = *(UInt32 *)data.bytes;
+    // http://www.w3.org/Graphics/GIF/spec-gif89a.txt
+    if ((magic & 0xFFFFFF) != '\0FIG') return NO;
+    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFTypeRef)data, NULL);
+    if (!source) return NO;
+    size_t count = CGImageSourceGetCount(source);
+    CFRelease(source);
+    return count > 1;
+}
+
++ (BOOL)isAnimatedGIFFile:(NSString *)path {
+    if (path.length == 0) return NO;
+    const char *cpath = path.UTF8String;
+    FILE *fd = fopen(cpath, "rb");
+    if (!fd) return NO;
+    
+    BOOL isGIF = NO;
+    UInt32 magic = 0;
+    if (fread(&magic, sizeof(UInt32), 1, fd) == 1) {
+        if ((magic & 0xFFFFFF) == '\0FIG') isGIF = YES;
+    }
+    fclose(fd);
+    return isGIF;
+}
+
++ (UIImage *)imageWithPDF:(id)dataOrPath {
+    return [self _yy_imageWithPDF:dataOrPath resize:NO size:CGSizeZero];
+}
+
++ (UIImage *)imageWithPDF:(id)dataOrPath size:(CGSize)size {
+    return [self _yy_imageWithPDF:dataOrPath resize:YES size:size];
+}
+
++ (UIImage *)imageWithEmoji:(NSString *)emoji size:(CGFloat)size {
+    if (emoji.length == 0) return nil;
+    if (size < 1) return nil;
+    
+    CGFloat scale = [UIScreen mainScreen].scale;
+    CTFontRef font = CTFontCreateWithName(CFSTR("AppleColorEmoji"), size * scale, NULL);
+    if (!font) return nil;
+    
+    NSAttributedString *str = [[NSAttributedString alloc] initWithString:emoji attributes:@{ (__bridge id)kCTFontAttributeName:(__bridge id)font, (__bridge id)kCTForegroundColorAttributeName:(__bridge id)[UIColor whiteColor].CGColor }];
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGContextRef ctx = CGBitmapContextCreate(NULL, size * scale, size * scale, 8, 0, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
+    CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
+    CTLineRef line = CTLineCreateWithAttributedString((__bridge CFTypeRef)str);
+    CGRect bounds = CTLineGetBoundsWithOptions(line, kCTLineBoundsUseGlyphPathBounds);
+    CGContextSetTextPosition(ctx, 0, -bounds.origin.y);
+    CTLineDraw(line, ctx);
+    CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
+    UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
+    
+    CFRelease(font);
+    CGColorSpaceRelease(colorSpace);
+    CGContextRelease(ctx);
+    if (line)CFRelease(line);
+    if (imageRef) CFRelease(imageRef);
+    
+    return image;
+}
+
++ (UIImage *)_yy_imageWithPDF:(id)dataOrPath resize:(BOOL)resize size:(CGSize)size {
+    CGPDFDocumentRef pdf = NULL;
+    if ([dataOrPath isKindOfClass:[NSData class]]) {
+        CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)dataOrPath);
+        pdf = CGPDFDocumentCreateWithProvider(provider);
+        CGDataProviderRelease(provider);
+    } else if ([dataOrPath isKindOfClass:[NSString class]]) {
+        pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:dataOrPath]);
+    }
+    if (!pdf) return nil;
+    
+    CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
+    if (!page) {
+        CGPDFDocumentRelease(pdf);
+        return nil;
+    }
+    
+    CGRect pdfRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
+    CGSize pdfSize = resize ? size : pdfRect.size;
+    CGFloat scale = [UIScreen mainScreen].scale;
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGContextRef ctx = CGBitmapContextCreate(NULL, pdfSize.width * scale, pdfSize.height * scale, 8, 0, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
+    if (!ctx) {
+        CGColorSpaceRelease(colorSpace);
+        CGPDFDocumentRelease(pdf);
+        return nil;
+    }
+    
+    CGContextScaleCTM(ctx, scale, scale);
+    CGContextTranslateCTM(ctx, -pdfRect.origin.x, -pdfRect.origin.y);
+    CGContextDrawPDFPage(ctx, page);
+    CGPDFDocumentRelease(pdf);
+    
+    CGImageRef image = CGBitmapContextCreateImage(ctx);
+    UIImage *pdfImage = [[UIImage alloc] initWithCGImage:image scale:scale orientation:UIImageOrientationUp];
+    CGImageRelease(image);
+    CGContextRelease(ctx);
+    CGColorSpaceRelease(colorSpace);
+    
+    return pdfImage;
+}
+
++ (UIImage *)imageWithColor:(UIColor *)color {
+    return [self imageWithColor:color size:CGSizeMake(1, 1)];
+}
+
++ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
+    if (!color || size.width <= 0 || size.height <= 0) return nil;
+    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
+    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
+    CGContextRef context = UIGraphicsGetCurrentContext();
+    CGContextSetFillColorWithColor(context, color.CGColor);
+    CGContextFillRect(context, rect);
+    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return image;
+}
+
++ (UIImage *)imageWithSize:(CGSize)size drawBlock:(void (^)(CGContextRef context))drawBlock {
+    if (!drawBlock) return nil;
+    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
+    CGContextRef context = UIGraphicsGetCurrentContext();
+    if (!context) return nil;
+    drawBlock(context);
+    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return image;
+}
+
+- (BOOL)hasAlphaChannel {
+    if (self.CGImage == NULL) return NO;
+    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage) & kCGBitmapAlphaInfoMask;
+    return (alpha == kCGImageAlphaFirst ||
+            alpha == kCGImageAlphaLast ||
+            alpha == kCGImageAlphaPremultipliedFirst ||
+            alpha == kCGImageAlphaPremultipliedLast);
+}
+
+- (void)drawInRect:(CGRect)rect withContentMode:(UIViewContentMode)contentMode clipsToBounds:(BOOL)clips{
+    CGRect drawRect = YYCGRectFitWithContentMode(rect, self.size, contentMode);
+    if (drawRect.size.width == 0 || drawRect.size.height == 0) return;
+    if (clips) {
+        CGContextRef context = UIGraphicsGetCurrentContext();
+        if (context) {
+            CGContextSaveGState(context);
+            CGContextAddRect(context, rect);
+            CGContextClip(context);
+            [self drawInRect:drawRect];
+            CGContextRestoreGState(context);
+        }
+    } else {
+        [self drawInRect:drawRect];
+    }
+}
+
+- (UIImage *)imageByResizeToSize:(CGSize)size {
+    if (size.width <= 0 || size.height <= 0) return nil;
+    UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);
+    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
+    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return image;
+}
+
+- (UIImage *)imageByResizeToSize:(CGSize)size contentMode:(UIViewContentMode)contentMode {
+    if (size.width <= 0 || size.height <= 0) return nil;
+    UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);
+    [self drawInRect:CGRectMake(0, 0, size.width, size.height) withContentMode:contentMode clipsToBounds:NO];
+    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return image;
+}
+
+- (UIImage *)imageByCropToRect:(CGRect)rect {
+    rect.origin.x *= self.scale;
+    rect.origin.y *= self.scale;
+    rect.size.width *= self.scale;
+    rect.size.height *= self.scale;
+    if (rect.size.width <= 0 || rect.size.height <= 0) return nil;
+    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
+    UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
+    CGImageRelease(imageRef);
+    return image;
+}
+
+- (UIImage *)imageByInsetEdge:(UIEdgeInsets)insets withColor:(UIColor *)color {
+    CGSize size = self.size;
+    size.width -= insets.left + insets.right;
+    size.height -= insets.top + insets.bottom;
+    if (size.width <= 0 || size.height <= 0) return nil;
+    CGRect rect = CGRectMake(-insets.left, -insets.top, self.size.width, self.size.height);
+    UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);
+    CGContextRef context = UIGraphicsGetCurrentContext();
+    if (color) {
+        CGContextSetFillColorWithColor(context, color.CGColor);
+        CGMutablePathRef path = CGPathCreateMutable();
+        CGPathAddRect(path, NULL, CGRectMake(0, 0, size.width, size.height));
+        CGPathAddRect(path, NULL, rect);
+        CGContextAddPath(context, path);
+        CGContextEOFillPath(context);
+        CGPathRelease(path);
+    }
+    [self drawInRect:rect];
+    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return image;
+}
+
+- (UIImage *)imageByRoundCornerRadius:(CGFloat)radius {
+    return [self imageByRoundCornerRadius:radius borderWidth:0 borderColor:nil];
+}
+
+- (UIImage *)imageByRoundCornerRadius:(CGFloat)radius
+                          borderWidth:(CGFloat)borderWidth
+                          borderColor:(UIColor *)borderColor {
+    return [self imageByRoundCornerRadius:radius
+                                  corners:UIRectCornerAllCorners
+                              borderWidth:borderWidth
+                              borderColor:borderColor
+                           borderLineJoin:kCGLineJoinMiter];
+}
+
+- (UIImage *)imageByRoundCornerRadius:(CGFloat)radius
+                              corners:(UIRectCorner)corners
+                          borderWidth:(CGFloat)borderWidth
+                          borderColor:(UIColor *)borderColor
+                       borderLineJoin:(CGLineJoin)borderLineJoin {
+    
+    if (corners != UIRectCornerAllCorners) {
+        UIRectCorner tmp = 0;
+        if (corners & UIRectCornerTopLeft) tmp |= UIRectCornerBottomLeft;
+        if (corners & UIRectCornerTopRight) tmp |= UIRectCornerBottomRight;
+        if (corners & UIRectCornerBottomLeft) tmp |= UIRectCornerTopLeft;
+        if (corners & UIRectCornerBottomRight) tmp |= UIRectCornerTopRight;
+        corners = tmp;
+    }
+    
+    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
+    CGContextRef context = UIGraphicsGetCurrentContext();
+    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
+    CGContextScaleCTM(context, 1, -1);
+    CGContextTranslateCTM(context, 0, -rect.size.height);
+    
+    CGFloat minSize = MIN(self.size.width, self.size.height);
+    if (borderWidth < minSize / 2) {
+        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadii:CGSizeMake(radius, borderWidth)];
+        [path closePath];
+        
+        CGContextSaveGState(context);
+        [path addClip];
+        CGContextDrawImage(context, rect, self.CGImage);
+        CGContextRestoreGState(context);
+    }
+    
+    if (borderColor && borderWidth < minSize / 2 && borderWidth > 0) {
+        CGFloat strokeInset = (floor(borderWidth * self.scale) + 0.5) / self.scale;
+        CGRect strokeRect = CGRectInset(rect, strokeInset, strokeInset);
+        CGFloat strokeRadius = radius > self.scale / 2 ? radius - self.scale / 2 : 0;
+        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadii:CGSizeMake(strokeRadius, borderWidth)];
+        [path closePath];
+        
+        path.lineWidth = borderWidth;
+        path.lineJoinStyle = borderLineJoin;
+        [borderColor setStroke];
+        [path stroke];
+    }
+    
+    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return image;
+}
+
+- (UIImage *)imageByRotate:(CGFloat)radians fitSize:(BOOL)fitSize {
+    size_t width = (size_t)CGImageGetWidth(self.CGImage);
+    size_t height = (size_t)CGImageGetHeight(self.CGImage);
+    CGRect newRect = CGRectApplyAffineTransform(CGRectMake(0., 0., width, height),
+                                                fitSize ? CGAffineTransformMakeRotation(radians) : CGAffineTransformIdentity);
+    
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGContextRef context = CGBitmapContextCreate(NULL,
+                                                 (size_t)newRect.size.width,
+                                                 (size_t)newRect.size.height,
+                                                 8,
+                                                 (size_t)newRect.size.width * 4,
+                                                 colorSpace,
+                                                 kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
+    CGColorSpaceRelease(colorSpace);
+    if (!context) return nil;
+    
+    CGContextSetShouldAntialias(context, true);
+    CGContextSetAllowsAntialiasing(context, true);
+    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
+    
+    CGContextTranslateCTM(context, +(newRect.size.width * 0.5), +(newRect.size.height * 0.5));
+    CGContextRotateCTM(context, radians);
+    
+    CGContextDrawImage(context, CGRectMake(-(width * 0.5), -(height * 0.5), width, height), self.CGImage);
+    CGImageRef imgRef = CGBitmapContextCreateImage(context);
+    UIImage *img = [UIImage imageWithCGImage:imgRef scale:self.scale orientation:self.imageOrientation];
+    CGImageRelease(imgRef);
+    CGContextRelease(context);
+    return img;
+}
+
+- (UIImage *)_yy_flipHorizontal:(BOOL)horizontal vertical:(BOOL)vertical {
+    if (!self.CGImage) return nil;
+    size_t width = (size_t)CGImageGetWidth(self.CGImage);
+    size_t height = (size_t)CGImageGetHeight(self.CGImage);
+    size_t bytesPerRow = width * 4;
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
+    CGColorSpaceRelease(colorSpace);
+    if (!context) return nil;
+    
+    CGContextDrawImage(context, CGRectMake(0, 0, width, height), self.CGImage);
+    UInt8 *data = (UInt8 *)CGBitmapContextGetData(context);
+    if (!data) {
+        CGContextRelease(context);
+        return nil;
+    }
+    vImage_Buffer src = { data, height, width, bytesPerRow };
+    vImage_Buffer dest = { data, height, width, bytesPerRow };
+    if (vertical) {
+        vImageVerticalReflect_ARGB8888(&src, &dest, kvImageBackgroundColorFill);
+    }
+    if (horizontal) {
+        vImageHorizontalReflect_ARGB8888(&src, &dest, kvImageBackgroundColorFill);
+    }
+    CGImageRef imgRef = CGBitmapContextCreateImage(context);
+    CGContextRelease(context);
+    UIImage *img = [UIImage imageWithCGImage:imgRef scale:self.scale orientation:self.imageOrientation];
+    CGImageRelease(imgRef);
+    return img;
+}
+
+- (UIImage *)imageByRotateLeft90 {
+    return [self imageByRotate:DegreesToRadians(90) fitSize:YES];
+}
+
+- (UIImage *)imageByRotateRight90 {
+    return [self imageByRotate:DegreesToRadians(-90) fitSize:YES];
+}
+
+- (UIImage *)imageByRotate180 {
+    return [self _yy_flipHorizontal:YES vertical:YES];
+}
+
+- (UIImage *)imageByFlipVertical {
+    return [self _yy_flipHorizontal:NO vertical:YES];
+}
+
+- (UIImage *)imageByFlipHorizontal {
+    return [self _yy_flipHorizontal:YES vertical:NO];
+}
+
+- (UIImage *)imageByTintColor:(UIColor *)color {
+    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
+    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
+    [color set];
+    UIRectFill(rect);
+    [self drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeDestinationIn alpha:1];
+    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return newImage;
+}
+
+- (UIImage *)imageByGrayscale {
+    return [self imageByBlurRadius:0 tintColor:nil tintMode:0 saturation:0 maskImage:nil];
+}
+
+- (UIImage *)imageByBlurSoft {
+    return [self imageByBlurRadius:60 tintColor:[UIColor colorWithWhite:0.84 alpha:0.36] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
+}
+
+- (UIImage *)imageByBlurLight {
+    return [self imageByBlurRadius:60 tintColor:[UIColor colorWithWhite:1.0 alpha:0.3] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
+}
+
+- (UIImage *)imageByBlurExtraLight {
+    return [self imageByBlurRadius:40 tintColor:[UIColor colorWithWhite:0.97 alpha:0.82] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
+}
+
+- (UIImage *)imageByBlurDark {
+    return [self imageByBlurRadius:40 tintColor:[UIColor colorWithWhite:0.11 alpha:0.73] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
+}
+
+- (UIImage *)imageByBlurWithTint:(UIColor *)tintColor {
+    const CGFloat EffectColorAlpha = 0.6;
+    UIColor *effectColor = tintColor;
+    size_t componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
+    if (componentCount == 2) {
+        CGFloat b;
+        if ([tintColor getWhite:&b alpha:NULL]) {
+            effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
+        }
+    } else {
+        CGFloat r, g, b;
+        if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
+            effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
+        }
+    }
+    return [self imageByBlurRadius:20 tintColor:effectColor tintMode:kCGBlendModeNormal saturation:-1.0 maskImage:nil];
+}
+
+- (UIImage *)imageByBlurRadius:(CGFloat)blurRadius
+                     tintColor:(UIColor *)tintColor
+                      tintMode:(CGBlendMode)tintBlendMode
+                    saturation:(CGFloat)saturation
+                     maskImage:(UIImage *)maskImage {
+    if (self.size.width < 1 || self.size.height < 1) {
+        NSLog(@"UIImage+YYAdd error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
+        return nil;
+    }
+    if (!self.CGImage) {
+        NSLog(@"UIImage+YYAdd error: inputImage must be backed by a CGImage: %@", self);
+        return nil;
+    }
+    if (maskImage && !maskImage.CGImage) {
+        NSLog(@"UIImage+YYAdd error: effectMaskImage must be backed by a CGImage: %@", maskImage);
+        return nil;
+    }
+    
+    // iOS7 and above can use new func.
+    BOOL hasNewFunc = (long)vImageBuffer_InitWithCGImage != 0 && (long)vImageCreateCGImageFromBuffer != 0;
+    BOOL hasBlur = blurRadius > __FLT_EPSILON__;
+    BOOL hasSaturation = fabs(saturation - 1.0) > __FLT_EPSILON__;
+    
+    CGSize size = self.size;
+    CGRect rect = { CGPointZero, size };
+    CGFloat scale = self.scale;
+    CGImageRef imageRef = self.CGImage;
+    BOOL opaque = NO;
+    
+    if (!hasBlur && !hasSaturation) {
+        return [self _yy_mergeImageRef:imageRef tintColor:tintColor tintBlendMode:tintBlendMode maskImage:maskImage opaque:opaque];
+    }
+    
+    vImage_Buffer effect = { 0 }, scratch = { 0 };
+    vImage_Buffer *input = NULL, *output = NULL;
+    
+    vImage_CGImageFormat format = {
+        .bitsPerComponent = 8,
+        .bitsPerPixel = 32,
+        .colorSpace = NULL,
+        .bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little, //requests a BGRA buffer.
+        .version = 0,
+        .decode = NULL,
+        .renderingIntent = kCGRenderingIntentDefault
+    };
+    
+    if (hasNewFunc) {
+        vImage_Error err;
+        err = vImageBuffer_InitWithCGImage(&effect, &format, NULL, imageRef, kvImagePrintDiagnosticsToConsole);
+        if (err != kvImageNoError) {
+            NSLog(@"UIImage+YYAdd error: vImageBuffer_InitWithCGImage returned error code %zi for inputImage: %@", err, self);
+            return nil;
+        }
+        err = vImageBuffer_Init(&scratch, effect.height, effect.width, format.bitsPerPixel, kvImageNoFlags);
+        if (err != kvImageNoError) {
+            NSLog(@"UIImage+YYAdd error: vImageBuffer_Init returned error code %zi for inputImage: %@", err, self);
+            return nil;
+        }
+    } else {
+        UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
+        CGContextRef effectCtx = UIGraphicsGetCurrentContext();
+        CGContextScaleCTM(effectCtx, 1.0, -1.0);
+        CGContextTranslateCTM(effectCtx, 0, -size.height);
+        CGContextDrawImage(effectCtx, rect, imageRef);
+        effect.data     = CGBitmapContextGetData(effectCtx);
+        effect.width    = CGBitmapContextGetWidth(effectCtx);
+        effect.height   = CGBitmapContextGetHeight(effectCtx);
+        effect.rowBytes = CGBitmapContextGetBytesPerRow(effectCtx);
+        
+        UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
+        CGContextRef scratchCtx = UIGraphicsGetCurrentContext();
+        scratch.data     = CGBitmapContextGetData(scratchCtx);
+        scratch.width    = CGBitmapContextGetWidth(scratchCtx);
+        scratch.height   = CGBitmapContextGetHeight(scratchCtx);
+        scratch.rowBytes = CGBitmapContextGetBytesPerRow(scratchCtx);
+    }
+    
+    input = &effect;
+    output = &scratch;
+    
+    if (hasBlur) {
+        // A description of how to compute the box kernel width from the Gaussian
+        // radius (aka standard deviation) appears in the SVG spec:
+        // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
+        //
+        // For larger values of 's' (s >= 2.0), an approximation can be used: Three
+        // successive box-blurs build a piece-wise quadratic convolution kernel, which
+        // approximates the Gaussian kernel to within roughly 3%.
+        //
+        // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
+        //
+        // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
+        //
+        CGFloat inputRadius = blurRadius * scale;
+        if (inputRadius - 2.0 < __FLT_EPSILON__) inputRadius = 2.0;
+        uint32_t radius = floor((inputRadius * 3.0 * sqrt(2 * M_PI) / 4 + 0.5) / 2);
+        radius |= 1; // force radius to be odd so that the three box-blur methodology works.
+        int iterations;
+        if (blurRadius * scale < 0.5) iterations = 1;
+        else if (blurRadius * scale < 1.5) iterations = 2;
+        else iterations = 3;
+        NSInteger tempSize = vImageBoxConvolve_ARGB8888(input, output, NULL, 0, 0, radius, radius, NULL, kvImageGetTempBufferSize | kvImageEdgeExtend);
+        void *temp = malloc(tempSize);
+        for (int i = 0; i < iterations; i++) {
+            vImageBoxConvolve_ARGB8888(input, output, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend);
+            YY_SWAP(input, output);
+        }
+        free(temp);
+    }
+    
+    
+    if (hasSaturation) {
+        // These values appear in the W3C Filter Effects spec:
+        // https://dvcs.w3.org/hg/FXTF/raw-file/default/filters/Publish.html#grayscaleEquivalent
+        CGFloat s = saturation;
+        CGFloat matrixFloat[] = {
+            0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
+            0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
+            0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
+            0,                    0,                    0,                    1,
+        };
+        const int32_t divisor = 256;
+        NSUInteger matrixSize = sizeof(matrixFloat) / sizeof(matrixFloat[0]);
+        int16_t matrix[matrixSize];
+        for (NSUInteger i = 0; i < matrixSize; ++i) {
+            matrix[i] = (int16_t)roundf(matrixFloat[i] * divisor);
+        }
+        vImageMatrixMultiply_ARGB8888(input, output, matrix, divisor, NULL, NULL, kvImageNoFlags);
+        YY_SWAP(input, output);
+    }
+    
+    UIImage *outputImage = nil;
+    if (hasNewFunc) {
+        CGImageRef effectCGImage = NULL;
+        effectCGImage = vImageCreateCGImageFromBuffer(input, &format, &_yy_cleanupBuffer, NULL, kvImageNoAllocate, NULL);
+        if (effectCGImage == NULL) {
+            effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoFlags, NULL);
+            free(input->data);
+        }
+        free(output->data);
+        outputImage = [self _yy_mergeImageRef:effectCGImage tintColor:tintColor tintBlendMode:tintBlendMode maskImage:maskImage opaque:opaque];
+        CGImageRelease(effectCGImage);
+    } else {
+        CGImageRef effectCGImage;
+        UIImage *effectImage;
+        if (input != &effect) effectImage = UIGraphicsGetImageFromCurrentImageContext();
+        UIGraphicsEndImageContext();
+        if (input == &effect) effectImage = UIGraphicsGetImageFromCurrentImageContext();
+        UIGraphicsEndImageContext();
+        effectCGImage = effectImage.CGImage;
+        outputImage = [self _yy_mergeImageRef:effectCGImage tintColor:tintColor tintBlendMode:tintBlendMode maskImage:maskImage opaque:opaque];
+    }
+    return outputImage;
+}
+
+// Helper function to handle deferred cleanup of a buffer.
+static void _yy_cleanupBuffer(void *userData, void *buf_data) {
+    free(buf_data);
+}
+
+// Helper function to add tint and mask.
+- (UIImage *)_yy_mergeImageRef:(CGImageRef)effectCGImage
+                     tintColor:(UIColor *)tintColor
+                 tintBlendMode:(CGBlendMode)tintBlendMode
+                     maskImage:(UIImage *)maskImage
+                        opaque:(BOOL)opaque {
+    BOOL hasTint = tintColor != nil && CGColorGetAlpha(tintColor.CGColor) > __FLT_EPSILON__;
+    BOOL hasMask = maskImage != nil;
+    CGSize size = self.size;
+    CGRect rect = { CGPointZero, size };
+    CGFloat scale = self.scale;
+    
+    if (!hasTint && !hasMask) {
+        return [UIImage imageWithCGImage:effectCGImage];
+    }
+    
+    UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
+    CGContextRef context = UIGraphicsGetCurrentContext();
+    CGContextScaleCTM(context, 1.0, -1.0);
+    CGContextTranslateCTM(context, 0, -size.height);
+    if (hasMask) {
+        CGContextDrawImage(context, rect, self.CGImage);
+        CGContextSaveGState(context);
+        CGContextClipToMask(context, rect, maskImage.CGImage);
+    }
+    CGContextDrawImage(context, rect, effectCGImage);
+    if (hasTint) {
+        CGContextSaveGState(context);
+        CGContextSetBlendMode(context, tintBlendMode);
+        CGContextSetFillColorWithColor(context, tintColor.CGColor);
+        CGContextFillRect(context, rect);
+        CGContextRestoreGState(context);
+    }
+    if (hasMask) {
+        CGContextRestoreGState(context);
+    }
+    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return outputImage;
+}
+
+@end

+ 63 - 0
YYKit/Base/UIKit/UIScreen+YYAdd.h

@@ -0,0 +1,63 @@
+//
+//  UIScreen+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/5.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIScreen`.
+ */
+@interface UIScreen (YYAdd)
+
+/**
+ Main screen's scale
+ 
+ @return screen's scale
+ */
++ (CGFloat)screenScale;
+
+/**
+ Returns the bounds of the screen for the current device orientation.
+ 
+ @return A rect indicating the bounds of the screen.
+ @see    boundsForOrientation:
+ */
+- (CGRect)currentBounds NS_EXTENSION_UNAVAILABLE_IOS("");
+
+/**
+ Returns the bounds of the screen for a given device orientation.
+ `UIScreen`'s `bounds` method always returns the bounds of the
+ screen of it in the portrait orientation.
+ 
+ @param orientation  The orientation to get the screen's bounds.
+ @return A rect indicating the bounds of the screen.
+ @see  currentBounds
+ */
+- (CGRect)boundsForOrientation:(UIInterfaceOrientation)orientation;
+
+/**
+ The screen's real size in pixel (width is always smaller than height).
+ This value may not be very accurate in an unknown device, or simulator.
+ e.g. (768,1024)
+ */
+@property (nonatomic, readonly) CGSize sizeInPixel;
+
+/**
+ The screen's PPI.
+ This value may not be very accurate in an unknown device, or simulator.
+ Default value is 96.
+ */
+@property (nonatomic, readonly) CGFloat pixelsPerInch;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 174 - 0
YYKit/Base/UIKit/UIScreen+YYAdd.m

@@ -0,0 +1,174 @@
+//
+//  UIScreen+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/5.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIScreen+YYAdd.h"
+#import "YYKitMacro.h"
+#import "UIDevice+YYAdd.h"
+
+YYSYNTH_DUMMY_CLASS(UIScreen_YYAdd);
+
+
+@implementation UIScreen (YYAdd)
+
++ (CGFloat)screenScale {
+    static CGFloat screenScale = 0.0;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        if ([NSThread isMainThread]) {
+            screenScale = [[UIScreen mainScreen] scale];
+        } else {
+            dispatch_sync(dispatch_get_main_queue(), ^{
+                screenScale = [[UIScreen mainScreen] scale];
+            });
+        }
+    });
+    return screenScale;
+}
+
+- (CGRect)currentBounds {
+    return [self boundsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
+}
+
+- (CGRect)boundsForOrientation:(UIInterfaceOrientation)orientation {
+    CGRect bounds = [self bounds];
+    
+    if (UIInterfaceOrientationIsLandscape(orientation)) {
+        CGFloat buffer = bounds.size.width;
+        bounds.size.width = bounds.size.height;
+        bounds.size.height = buffer;
+    }
+    return bounds;
+}
+
+- (CGSize)sizeInPixel {
+    CGSize size = CGSizeZero;
+    
+    if ([[UIScreen mainScreen] isEqual:self]) {
+        NSString *model = [UIDevice currentDevice].machineModel;
+        
+        if ([model hasPrefix:@"iPhone"]) {
+            if ([model isEqualToString:@"iPhone7,1"]) return CGSizeMake(1080, 1920);
+            if ([model isEqualToString:@"iPhone8,2"]) return CGSizeMake(1080, 1920);
+            if ([model isEqualToString:@"iPhone9,2"]) return CGSizeMake(1080, 1920);
+            if ([model isEqualToString:@"iPhone9,4"]) return CGSizeMake(1080, 1920);
+        }
+        if ([model hasPrefix:@"iPad"]) {
+            if ([model hasPrefix:@"iPad6,7"]) size = CGSizeMake(2048, 2732);
+            if ([model hasPrefix:@"iPad6,8"]) size = CGSizeMake(2048, 2732);
+        }
+    }
+    
+    if (CGSizeEqualToSize(size, CGSizeZero)) {
+        if ([self respondsToSelector:@selector(nativeBounds)]) {
+            size = self.nativeBounds.size;
+        } else {
+            size = self.bounds.size;
+            size.width *= self.scale;
+            size.height *= self.scale;
+        }
+        if (size.height < size.width) {
+            CGFloat tmp = size.height;
+            size.height = size.width;
+            size.width = tmp;
+        }
+    }
+    return size;
+}
+
+- (CGFloat)pixelsPerInch {
+    if (![[UIScreen mainScreen] isEqual:self]) {
+        return 326;
+    }
+    
+    static CGFloat ppi = 0;
+    static dispatch_once_t one;
+    static NSString *name;
+    dispatch_once(&one, ^{
+        NSDictionary<NSString*, NSNumber *> *dic = @{
+            @"Watch1,1" : @326, //@"Apple Watch 38mm",
+            @"Watch1,2" : @326, //@"Apple Watch 43mm",
+            @"Watch2,3" : @326, //@"Apple Watch Series 2 38mm",
+            @"Watch2,4" : @326, //@"Apple Watch Series 2 42mm",
+            @"Watch2,6" : @326, //@"Apple Watch Series 1 38mm",
+            @"Watch1,7" : @326, //@"Apple Watch Series 1 42mm",
+
+            @"iPod1,1" : @163, //@"iPod touch 1",
+            @"iPod2,1" : @163, //@"iPod touch 2",
+            @"iPod3,1" : @163, //@"iPod touch 3",
+            @"iPod4,1" : @326, //@"iPod touch 4",
+            @"iPod5,1" : @326, //@"iPod touch 5",
+            @"iPod7,1" : @326, //@"iPod touch 6",
+
+            @"iPhone1,1" : @163, //@"iPhone 1G",
+            @"iPhone1,2" : @163, //@"iPhone 3G",
+            @"iPhone2,1" : @163, //@"iPhone 3GS",
+            @"iPhone3,1" : @326, //@"iPhone 4 (GSM)",
+            @"iPhone3,2" : @326, //@"iPhone 4",
+            @"iPhone3,3" : @326, //@"iPhone 4 (CDMA)",
+            @"iPhone4,1" : @326, //@"iPhone 4S",
+            @"iPhone5,1" : @326, //@"iPhone 5",
+            @"iPhone5,2" : @326, //@"iPhone 5",
+            @"iPhone5,3" : @326, //@"iPhone 5c",
+            @"iPhone5,4" : @326, //@"iPhone 5c",
+            @"iPhone6,1" : @326, //@"iPhone 5s",
+            @"iPhone6,2" : @326, //@"iPhone 5s",
+            @"iPhone7,1" : @401, //@"iPhone 6 Plus",
+            @"iPhone7,2" : @326, //@"iPhone 6",
+            @"iPhone8,1" : @326, //@"iPhone 6s",
+            @"iPhone8,2" : @401, //@"iPhone 6s Plus",
+            @"iPhone8,4" : @326, //@"iPhone SE",
+            @"iPhone9,1" : @326, //@"iPhone 7",
+            @"iPhone9,2" : @401, //@"iPhone 7 Plus",
+            @"iPhone9,3" : @326, //@"iPhone 7",
+            @"iPhone9,4" : @401, //@"iPhone 7 Plus",
+
+            @"iPad1,1" : @132, //@"iPad 1",
+            @"iPad2,1" : @132, //@"iPad 2 (WiFi)",
+            @"iPad2,2" : @132, //@"iPad 2 (GSM)",
+            @"iPad2,3" : @132, //@"iPad 2 (CDMA)",
+            @"iPad2,4" : @132, //@"iPad 2",
+            @"iPad2,5" : @264, //@"iPad mini 1",
+            @"iPad2,6" : @264, //@"iPad mini 1",
+            @"iPad2,7" : @264, //@"iPad mini 1",
+            @"iPad3,1" : @324, //@"iPad 3 (WiFi)",
+            @"iPad3,2" : @324, //@"iPad 3 (4G)",
+            @"iPad3,3" : @324, //@"iPad 3 (4G)",
+            @"iPad3,4" : @324, //@"iPad 4",
+            @"iPad3,5" : @324, //@"iPad 4",
+            @"iPad3,6" : @324, //@"iPad 4",
+            @"iPad4,1" : @324, //@"iPad Air",
+            @"iPad4,2" : @324, //@"iPad Air",
+            @"iPad4,3" : @324, //@"iPad Air",
+            @"iPad4,4" : @264, //@"iPad mini 2",
+            @"iPad4,5" : @264, //@"iPad mini 2",
+            @"iPad4,6" : @264, //@"iPad mini 2",
+            @"iPad4,7" : @264, //@"iPad mini 3",
+            @"iPad4,8" : @264, //@"iPad mini 3",
+            @"iPad4,9" : @264, //@"iPad mini 3",
+            @"iPad5,1" : @264, //@"iPad mini 4",
+            @"iPad5,2" : @264, //@"iPad mini 4",
+            @"iPad5,3" : @324, //@"iPad Air 2",
+            @"iPad5,4" : @324, //@"iPad Air 2",
+            @"iPad6,3" : @324, //@"iPad Pro (9.7 inch)",
+            @"iPad6,4" : @324, //@"iPad Pro (9.7 inch)",
+            @"iPad6,7" : @264, //@"iPad Pro (12.9 inch)",
+            @"iPad6,8" : @264, //@"iPad Pro (12.9 inch)",
+            };
+        NSString *model = [UIDevice currentDevice].machineModel;
+        if (model) {
+            ppi = dic[name].doubleValue;
+        }
+        if (ppi == 0) ppi = 326;
+    });
+    return ppi;
+}
+
+@end

+ 71 - 0
YYKit/Base/UIKit/UIScrollView+YYAdd.h

@@ -0,0 +1,71 @@
+//
+//  UIScrollView+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/5.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIScrollView`.
+ */
+@interface UIScrollView (YYAdd)
+
+/**
+ Scroll content to top with animation.
+ */
+- (void)scrollToTop;
+
+/**
+ Scroll content to bottom with animation.
+ */
+- (void)scrollToBottom;
+
+/**
+ Scroll content to left with animation.
+ */
+- (void)scrollToLeft;
+
+/**
+ Scroll content to right with animation.
+ */
+- (void)scrollToRight;
+
+/**
+ Scroll content to top.
+ 
+ @param animated  Use animation.
+ */
+- (void)scrollToTopAnimated:(BOOL)animated;
+
+/**
+ Scroll content to bottom.
+ 
+ @param animated  Use animation.
+ */
+- (void)scrollToBottomAnimated:(BOOL)animated;
+
+/**
+ Scroll content to left.
+ 
+ @param animated  Use animation.
+ */
+- (void)scrollToLeftAnimated:(BOOL)animated;
+
+/**
+ Scroll content to right.
+ 
+ @param animated  Use animation.
+ */
+- (void)scrollToRightAnimated:(BOOL)animated;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 60 - 0
YYKit/Base/UIKit/UIScrollView+YYAdd.m

@@ -0,0 +1,60 @@
+//
+//  UIScrollView+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/5.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIScrollView+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(UIScrollView_YYAdd)
+
+
+@implementation UIScrollView (YYAdd)
+
+- (void)scrollToTop {
+    [self scrollToTopAnimated:YES];
+}
+
+- (void)scrollToBottom {
+    [self scrollToBottomAnimated:YES];
+}
+
+- (void)scrollToLeft {
+    [self scrollToLeftAnimated:YES];
+}
+
+- (void)scrollToRight {
+    [self scrollToRightAnimated:YES];
+}
+
+- (void)scrollToTopAnimated:(BOOL)animated {
+    CGPoint off = self.contentOffset;
+    off.y = 0 - self.contentInset.top;
+    [self setContentOffset:off animated:animated];
+}
+
+- (void)scrollToBottomAnimated:(BOOL)animated {
+    CGPoint off = self.contentOffset;
+    off.y = self.contentSize.height - self.bounds.size.height + self.contentInset.bottom;
+    [self setContentOffset:off animated:animated];
+}
+
+- (void)scrollToLeftAnimated:(BOOL)animated {
+    CGPoint off = self.contentOffset;
+    off.x = 0 - self.contentInset.left;
+    [self setContentOffset:off animated:animated];
+}
+
+- (void)scrollToRightAnimated:(BOOL)animated {
+    CGPoint off = self.contentOffset;
+    off.x = self.contentSize.width - self.bounds.size.width + self.contentInset.right;
+    [self setContentOffset:off animated:animated];
+}
+
+@end

+ 188 - 0
YYKit/Base/UIKit/UITableView+YYAdd.h

@@ -0,0 +1,188 @@
+//
+//  UITableView+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/12.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UITableView`.
+ */
+@interface UITableView (YYAdd)
+
+/**
+ Perform a series of method calls that insert, delete, or select rows and
+ sections of the receiver.
+ 
+ @discussion Perform a series of method calls that insert, delete, or select
+             rows and sections of the table. Call this method if you want
+             subsequent insertions, deletion, and selection operations (for
+             example, cellForRowAtIndexPath: and indexPathsForVisibleRows)
+             to be animated simultaneously.
+ 
+ @discussion If you do not make the insertion, deletion, and selection calls
+             inside this block, table attributes such as row count might become
+             invalid. You should not call reloadData within the block; if you
+             call this method within the group, you will need to perform any
+             animations yourself.
+ 
+ @param block  A block combine a series of method calls.
+ */
+- (void)updateWithBlock:(void (^)(UITableView *tableView))block;
+
+/**
+ Scrolls the receiver until a row or section location on the screen.
+ 
+ @discussion            Invoking this method does not cause the delegate to 
+                        receive a scrollViewDidScroll: message, as is normal for 
+                        programmatically-invoked user interface operations.
+ 
+ @param row             Row index in section. NSNotFound is a valid value for
+                        scrolling to a section with zero rows.
+ 
+ @param section         Section index in table.
+ 
+ @param scrollPosition  A constant that identifies a relative position in the 
+                        receiving table view (top, middle, bottom) for row when 
+                        scrolling concludes.
+ 
+ @param animated        YES if you want to animate the change in position,
+                        NO if it should be immediate.
+ */
+- (void)scrollToRow:(NSUInteger)row inSection:(NSUInteger)section atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
+
+/**
+ Inserts a row in the receiver with an option to animate the insertion.
+ 
+ @param row        Row index in section.
+ 
+ @param section    Section index in table.
+ 
+ @param animation  A constant that either specifies the kind of animation to
+                   perform when inserting the cell or requests no animation. 
+ */
+- (void)insertRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Reloads the specified row using a certain animation effect.
+ 
+ @param row        Row index in section.
+ 
+ @param section    Section index in table.
+ 
+ @param animation  A constant that indicates how the reloading is to be animated,
+                   for example, fade out or slide out from the bottom. The animation 
+                   constant affects the direction in which both the old and the 
+                   new rows slide. For example, if the animation constant is 
+                   UITableViewRowAnimationRight, the old rows slide out to the 
+                   right and the new cells slide in from the right.
+ */
+- (void)reloadRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Deletes the row with an option to animate the deletion.
+ 
+ @param row        Row index in section.
+ 
+ @param section    Section index in table.
+ 
+ @param animation  A constant that indicates how the deletion is to be animated, 
+                   for example, fade out or slide out from the bottom.
+ */
+- (void)deleteRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Inserts the row in the receiver at the locations identified by the indexPath, 
+ with an option to animate the insertion.
+ 
+ @param indexPath  An NSIndexPath object representing a row index and section 
+                   index that together identify a row in the table view.
+ 
+ @param animation  A constant that either specifies the kind of animation to
+                   perform when inserting the cell or requests no animation.
+ */
+- (void)insertRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Reloads the specified row using a certain animation effect.
+ 
+ @param indexPath  An NSIndexPath object representing a row index and section
+                   index that together identify a row in the table view.
+ 
+ @param animation A constant that indicates how the reloading is to be animated,
+                  for example, fade out or slide out from the bottom. The animation
+                  constant affects the direction in which both the old and the
+                  new rows slide. For example, if the animation constant is
+                  UITableViewRowAnimationRight, the old rows slide out to the
+                  right and the new cells slide in from the right.
+ */
+- (void)reloadRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Deletes the row specified by an array of index paths, 
+ with an option to animate the deletion.
+ 
+ @param indexPath  An NSIndexPath object representing a row index and section
+                   index that together identify a row in the table view.
+ 
+ @param animation  A constant that indicates how the deletion is to be animated,
+                   for example, fade out or slide out from the bottom.
+ */
+- (void)deleteRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Inserts a section in the receiver, with an option to animate the insertion.
+ 
+ @param section    An index specifies the section to insert in the receiving
+                   table view. If a section already exists at the specified 
+                   index location, it is moved down one index location.
+ 
+ @param animation  A constant that indicates how the insertion is to be animated, 
+                   for example, fade in or slide in from the left.
+ */
+- (void)insertSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Deletes a section in the receiver, with an option to animate the deletion.
+ 
+ @param section    An index that specifies the sections to delete from the 
+                   receiving table view. If a section exists after the specified
+                   index location, it is moved up one index location.
+ 
+ @param animation  A constant that either specifies the kind of animation to 
+                   perform when deleting the section or requests no animation.
+ */
+- (void)deleteSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Reloads the specified section using a given animation effect.
+ 
+ @param section    An index identifying the section to reload.
+ 
+ @param animation  A constant that indicates how the reloading is to be animated, 
+                   for example, fade out or slide out from the bottom. The 
+                   animation constant affects the direction in which both the 
+                   old and the new section rows slide. For example, if the 
+                   animation constant is UITableViewRowAnimationRight, the old 
+                   rows slide out to the right and the new cells slide in from the right.
+ */
+- (void)reloadSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
+
+/**
+ Unselect all rows in tableView.
+ 
+ @param animated YES to animate the transition, NO to make the transition immediate.
+ */
+- (void)clearSelectedRowsAnimated:(BOOL)animated;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 80 - 0
YYKit/Base/UIKit/UITableView+YYAdd.m

@@ -0,0 +1,80 @@
+//
+//  UITableView+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/12.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UITableView+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(UITableView_YYAdd)
+
+
+@implementation UITableView (YYAdd)
+
+- (void)updateWithBlock:(void (^)(UITableView *tableView))block {
+    [self beginUpdates];
+    block(self);
+    [self endUpdates];
+}
+
+- (void)scrollToRow:(NSUInteger)row inSection:(NSUInteger)section atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated {
+    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
+    [self scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:animated];
+}
+
+- (void)insertRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation {
+    [self insertRowsAtIndexPaths:@[indexPath] withRowAnimation:animation];
+}
+
+- (void)insertRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
+    NSIndexPath *toInsert = [NSIndexPath indexPathForRow:row inSection:section];
+    [self insertRowAtIndexPath:toInsert withRowAnimation:animation];
+}
+
+- (void)reloadRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation {
+    [self reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:animation];
+}
+
+- (void)reloadRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
+    NSIndexPath *toReload = [NSIndexPath indexPathForRow:row inSection:section];
+    [self reloadRowAtIndexPath:toReload withRowAnimation:animation];
+}
+
+- (void)deleteRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation {
+    [self deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:animation];
+}
+
+- (void)deleteRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
+    NSIndexPath *toDelete = [NSIndexPath indexPathForRow:row inSection:section];
+    [self deleteRowAtIndexPath:toDelete withRowAnimation:animation];
+}
+
+- (void)insertSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
+    NSIndexSet *sections = [NSIndexSet indexSetWithIndex:section];
+    [self insertSections:sections withRowAnimation:animation];
+}
+
+- (void)deleteSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
+    NSIndexSet *sections = [NSIndexSet indexSetWithIndex:section];
+    [self deleteSections:sections withRowAnimation:animation];
+}
+
+- (void)reloadSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
+    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:section];
+    [self reloadSections:indexSet withRowAnimation:animation];
+}
+
+- (void)clearSelectedRowsAnimated:(BOOL)animated {
+    NSArray *indexs = [self indexPathsForSelectedRows];
+    [indexs enumerateObjectsUsingBlock:^(NSIndexPath* path, NSUInteger idx, BOOL *stop) {
+        [self deselectRowAtIndexPath:path animated:animated];
+    }];
+}
+
+@end

+ 35 - 0
YYKit/Base/UIKit/UITextField+YYAdd.h

@@ -0,0 +1,35 @@
+//
+//  UITextField+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/12.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UITextField`.
+ */
+@interface UITextField (YYAdd)
+
+/**
+ Set all text selected.
+ */
+- (void)selectAllText;
+
+/**
+ Set text in range selected.
+ 
+ @param range  The range of selected text in a document.
+ */
+- (void)setSelectedRange:(NSRange)range;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 33 - 0
YYKit/Base/UIKit/UITextField+YYAdd.m

@@ -0,0 +1,33 @@
+//
+//  UITextField+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/5/12.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UITextField+YYAdd.h"
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(UITextField_YYAdd)
+
+
+@implementation UITextField (YYAdd)
+
+- (void)selectAllText {
+    UITextRange *range = [self textRangeFromPosition:self.beginningOfDocument toPosition:self.endOfDocument];
+    [self setSelectedTextRange:range];
+}
+
+- (void)setSelectedRange:(NSRange)range {
+    UITextPosition *beginning = self.beginningOfDocument;
+    UITextPosition *startPosition = [self positionFromPosition:beginning offset:range.location];
+    UITextPosition *endPosition = [self positionFromPosition:beginning offset:NSMaxRange(range)];
+    UITextRange *selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
+    [self setSelectedTextRange:selectionRange];
+}
+
+@end

+ 117 - 0
YYKit/Base/UIKit/UIView+YYAdd.h

@@ -0,0 +1,117 @@
+//
+//  UIView+YYAdd.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Provides extensions for `UIView`.
+ */
+@interface UIView (YYAdd)
+
+/**
+ Create a snapshot image of the complete view hierarchy.
+ */
+- (nullable UIImage *)snapshotImage;
+
+/**
+ Create a snapshot image of the complete view hierarchy.
+ @discussion It's faster than "snapshotImage", but may cause screen updates.
+ See -[UIView drawViewHierarchyInRect:afterScreenUpdates:] for more information.
+ */
+- (nullable UIImage *)snapshotImageAfterScreenUpdates:(BOOL)afterUpdates;
+
+/**
+ Create a snapshot PDF of the complete view hierarchy.
+ */
+- (nullable NSData *)snapshotPDF;
+
+/**
+ Shortcut to set the view.layer's shadow
+ 
+ @param color  Shadow Color
+ @param offset Shadow offset
+ @param radius Shadow radius
+ */
+- (void)setLayerShadow:(nullable UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius;
+
+/**
+ Remove all subviews.
+ 
+ @warning Never call this method inside your view's drawRect: method.
+ */
+- (void)removeAllSubviews;
+
+/**
+ Returns the view's view controller (may be nil).
+ */
+@property (nullable, nonatomic, readonly) UIViewController *viewController;
+
+/**
+ Returns the visible alpha on screen, taking into account superview and window.
+ */
+@property (nonatomic, readonly) CGFloat visibleAlpha;
+
+/**
+ Converts a point from the receiver's coordinate system to that of the specified view or window.
+ 
+ @param point A point specified in the local coordinate system (bounds) of the receiver.
+ @param view  The view or window into whose coordinate system point is to be converted. 
+    If view is nil, this method instead converts to window base coordinates.
+ @return The point converted to the coordinate system of view.
+ */
+- (CGPoint)convertPoint:(CGPoint)point toViewOrWindow:(nullable UIView *)view;
+
+/**
+ Converts a point from the coordinate system of a given view or window to that of the receiver.
+ 
+ @param point A point specified in the local coordinate system (bounds) of view.
+ @param view  The view or window with point in its coordinate system. 
+    If view is nil, this method instead converts from window base coordinates.
+ @return The point converted to the local coordinate system (bounds) of the receiver.
+ */
+- (CGPoint)convertPoint:(CGPoint)point fromViewOrWindow:(nullable UIView *)view;
+
+/**
+ Converts a rectangle from the receiver's coordinate system to that of another view or window.
+ 
+ @param rect A rectangle specified in the local coordinate system (bounds) of the receiver.
+ @param view The view or window that is the target of the conversion operation. If view is nil, this method instead converts to window base coordinates.
+ @return The converted rectangle.
+ */
+- (CGRect)convertRect:(CGRect)rect toViewOrWindow:(nullable UIView *)view;
+
+/**
+ Converts a rectangle from the coordinate system of another view or window to that of the receiver.
+ 
+ @param rect A rectangle specified in the local coordinate system (bounds) of view.
+ @param view The view or window with rect in its coordinate system.
+    If view is nil, this method instead converts from window base coordinates.
+ @return The converted rectangle.
+ */
+- (CGRect)convertRect:(CGRect)rect fromViewOrWindow:(nullable UIView *)view;
+
+
+@property (nonatomic) CGFloat left;        ///< Shortcut for frame.origin.x.
+@property (nonatomic) CGFloat top;         ///< Shortcut for frame.origin.y
+@property (nonatomic) CGFloat right;       ///< Shortcut for frame.origin.x + frame.size.width
+@property (nonatomic) CGFloat bottom;      ///< Shortcut for frame.origin.y + frame.size.height
+@property (nonatomic) CGFloat width;       ///< Shortcut for frame.size.width.
+@property (nonatomic) CGFloat height;      ///< Shortcut for frame.size.height.
+@property (nonatomic) CGFloat centerX;     ///< Shortcut for center.x
+@property (nonatomic) CGFloat centerY;     ///< Shortcut for center.y
+@property (nonatomic) CGPoint origin;      ///< Shortcut for frame.origin.
+@property (nonatomic) CGSize  size;        ///< Shortcut for frame.size.
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 272 - 0
YYKit/Base/UIKit/UIView+YYAdd.m

@@ -0,0 +1,272 @@
+//
+//  UIView+YYAdd.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/4/3.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIView+YYAdd.h"
+#import <QuartzCore/QuartzCore.h>
+#import "YYKitMacro.h"
+
+YYSYNTH_DUMMY_CLASS(UIView_YYAdd)
+
+
+@implementation UIView (YYAdd)
+
+- (UIImage *)snapshotImage {
+    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
+    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
+    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return snap;
+}
+
+- (UIImage *)snapshotImageAfterScreenUpdates:(BOOL)afterUpdates {
+    if (![self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
+        return [self snapshotImage];
+    }
+    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
+    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:afterUpdates];
+    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
+    UIGraphicsEndImageContext();
+    return snap;
+}
+
+- (NSData *)snapshotPDF {
+    CGRect bounds = self.bounds;
+    NSMutableData *data = [NSMutableData data];
+    CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)data);
+    CGContextRef context = CGPDFContextCreate(consumer, &bounds, NULL);
+    CGDataConsumerRelease(consumer);
+    if (!context) return nil;
+    CGPDFContextBeginPage(context, NULL);
+    CGContextTranslateCTM(context, 0, bounds.size.height);
+    CGContextScaleCTM(context, 1.0, -1.0);
+    [self.layer renderInContext:context];
+    CGPDFContextEndPage(context);
+    CGPDFContextClose(context);
+    CGContextRelease(context);
+    return data;
+}
+
+- (void)setLayerShadow:(UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius {
+    self.layer.shadowColor = color.CGColor;
+    self.layer.shadowOffset = offset;
+    self.layer.shadowRadius = radius;
+    self.layer.shadowOpacity = 1;
+    self.layer.shouldRasterize = YES;
+    self.layer.rasterizationScale = [UIScreen mainScreen].scale;
+}
+
+- (void)removeAllSubviews {
+    //[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
+    while (self.subviews.count) {
+        [self.subviews.lastObject removeFromSuperview];
+    }
+}
+
+
+- (UIViewController *)viewController {
+    for (UIView *view = self; view; view = view.superview) {
+        UIResponder *nextResponder = [view nextResponder];
+        if ([nextResponder isKindOfClass:[UIViewController class]]) {
+            return (UIViewController *)nextResponder;
+        }
+    }
+    return nil;
+}
+
+- (CGFloat)visibleAlpha {
+    if ([self isKindOfClass:[UIWindow class]]) {
+        if (self.hidden) return 0;
+        return self.alpha;
+    }
+    if (!self.window) return 0;
+    CGFloat alpha = 1;
+    UIView *v = self;
+    while (v) {
+        if (v.hidden) {
+            alpha = 0;
+            break;
+        }
+        alpha *= v.alpha;
+        v = v.superview;
+    }
+    return alpha;
+}
+
+- (CGPoint)convertPoint:(CGPoint)point toViewOrWindow:(UIView *)view {
+    if (!view) {
+        if ([self isKindOfClass:[UIWindow class]]) {
+            return [((UIWindow *)self) convertPoint:point toWindow:nil];
+        } else {
+            return [self convertPoint:point toView:nil];
+        }
+    }
+    
+    UIWindow *from = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
+    UIWindow *to = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
+    if ((!from || !to) || (from == to)) return [self convertPoint:point toView:view];
+    point = [self convertPoint:point toView:from];
+    point = [to convertPoint:point fromWindow:from];
+    point = [view convertPoint:point fromView:to];
+    return point;
+}
+
+- (CGPoint)convertPoint:(CGPoint)point fromViewOrWindow:(UIView *)view {
+    if (!view) {
+        if ([self isKindOfClass:[UIWindow class]]) {
+            return [((UIWindow *)self) convertPoint:point fromWindow:nil];
+        } else {
+            return [self convertPoint:point fromView:nil];
+        }
+    }
+    
+    UIWindow *from = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
+    UIWindow *to = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
+    if ((!from || !to) || (from == to)) return [self convertPoint:point fromView:view];
+    point = [from convertPoint:point fromView:view];
+    point = [to convertPoint:point fromWindow:from];
+    point = [self convertPoint:point fromView:to];
+    return point;
+}
+
+- (CGRect)convertRect:(CGRect)rect toViewOrWindow:(UIView *)view {
+    if (!view) {
+        if ([self isKindOfClass:[UIWindow class]]) {
+            return [((UIWindow *)self) convertRect:rect toWindow:nil];
+        } else {
+            return [self convertRect:rect toView:nil];
+        }
+    }
+    
+    UIWindow *from = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
+    UIWindow *to = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
+    if (!from || !to) return [self convertRect:rect toView:view];
+    if (from == to) return [self convertRect:rect toView:view];
+    rect = [self convertRect:rect toView:from];
+    rect = [to convertRect:rect fromWindow:from];
+    rect = [view convertRect:rect fromView:to];
+    return rect;
+}
+
+- (CGRect)convertRect:(CGRect)rect fromViewOrWindow:(UIView *)view {
+    if (!view) {
+        if ([self isKindOfClass:[UIWindow class]]) {
+            return [((UIWindow *)self) convertRect:rect fromWindow:nil];
+        } else {
+            return [self convertRect:rect fromView:nil];
+        }
+    }
+    
+    UIWindow *from = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
+    UIWindow *to = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
+    if ((!from || !to) || (from == to)) return [self convertRect:rect fromView:view];
+    rect = [from convertRect:rect fromView:view];
+    rect = [to convertRect:rect fromWindow:from];
+    rect = [self convertRect:rect fromView:to];
+    return rect;
+}
+
+- (CGFloat)left {
+    return self.frame.origin.x;
+}
+
+- (void)setLeft:(CGFloat)x {
+    CGRect frame = self.frame;
+    frame.origin.x = x;
+    self.frame = frame;
+}
+
+- (CGFloat)top {
+    return self.frame.origin.y;
+}
+
+- (void)setTop:(CGFloat)y {
+    CGRect frame = self.frame;
+    frame.origin.y = y;
+    self.frame = frame;
+}
+
+- (CGFloat)right {
+    return self.frame.origin.x + self.frame.size.width;
+}
+
+- (void)setRight:(CGFloat)right {
+    CGRect frame = self.frame;
+    frame.origin.x = right - frame.size.width;
+    self.frame = frame;
+}
+
+- (CGFloat)bottom {
+    return self.frame.origin.y + self.frame.size.height;
+}
+
+- (void)setBottom:(CGFloat)bottom {
+    CGRect frame = self.frame;
+    frame.origin.y = bottom - frame.size.height;
+    self.frame = frame;
+}
+
+- (CGFloat)width {
+    return self.frame.size.width;
+}
+
+- (void)setWidth:(CGFloat)width {
+    CGRect frame = self.frame;
+    frame.size.width = width;
+    self.frame = frame;
+}
+
+- (CGFloat)height {
+    return self.frame.size.height;
+}
+
+- (void)setHeight:(CGFloat)height {
+    CGRect frame = self.frame;
+    frame.size.height = height;
+    self.frame = frame;
+}
+
+- (CGFloat)centerX {
+    return self.center.x;
+}
+
+- (void)setCenterX:(CGFloat)centerX {
+    self.center = CGPointMake(centerX, self.center.y);
+}
+
+- (CGFloat)centerY {
+    return self.center.y;
+}
+
+- (void)setCenterY:(CGFloat)centerY {
+    self.center = CGPointMake(self.center.x, centerY);
+}
+
+- (CGPoint)origin {
+    return self.frame.origin;
+}
+
+- (void)setOrigin:(CGPoint)origin {
+    CGRect frame = self.frame;
+    frame.origin = origin;
+    self.frame = frame;
+}
+
+- (CGSize)size {
+    return self.frame.size;
+}
+
+- (void)setSize:(CGSize)size {
+    CGRect frame = self.frame;
+    frame.size = size;
+    self.frame = frame;
+}
+
+@end

+ 336 - 0
YYKit/Base/YYKitMacro.h

@@ -0,0 +1,336 @@
+//
+//  YYKitMacro.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 13/3/29.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+#import <sys/time.h>
+#import <pthread.h>
+
+#ifndef YYKitMacro_h
+#define YYKitMacro_h
+
+#ifdef __cplusplus
+#define YY_EXTERN_C_BEGIN  extern "C" {
+#define YY_EXTERN_C_END  }
+#else
+#define YY_EXTERN_C_BEGIN
+#define YY_EXTERN_C_END
+#endif
+
+
+YY_EXTERN_C_BEGIN
+
+#ifndef YY_CLAMP // return the clamped value
+#define YY_CLAMP(_x_, _low_, _high_)  (((_x_) > (_high_)) ? (_high_) : (((_x_) < (_low_)) ? (_low_) : (_x_)))
+#endif
+
+#ifndef YY_SWAP // swap two value
+#define YY_SWAP(_a_, _b_)  do { __typeof__(_a_) _tmp_ = (_a_); (_a_) = (_b_); (_b_) = _tmp_; } while (0)
+#endif
+
+
+#define YYAssertNil(condition, description, ...) NSAssert(!(condition), (description), ##__VA_ARGS__)
+#define YYCAssertNil(condition, description, ...) NSCAssert(!(condition), (description), ##__VA_ARGS__)
+
+#define YYAssertNotNil(condition, description, ...) NSAssert((condition), (description), ##__VA_ARGS__)
+#define YYCAssertNotNil(condition, description, ...) NSCAssert((condition), (description), ##__VA_ARGS__)
+
+#define YYAssertMainThread() NSAssert([NSThread isMainThread], @"This method must be called on the main thread")
+#define YYCAssertMainThread() NSCAssert([NSThread isMainThread], @"This method must be called on the main thread")
+
+
+/**
+ Add this macro before each category implementation, so we don't have to use
+ -all_load or -force_load to load object files from static libraries that only
+ contain categories and no classes.
+ More info: http://developer.apple.com/library/mac/#qa/qa2006/qa1490.html .
+ *******************************************************************************
+ Example:
+     YYSYNTH_DUMMY_CLASS(NSString_YYAdd)
+ */
+#ifndef YYSYNTH_DUMMY_CLASS
+#define YYSYNTH_DUMMY_CLASS(_name_) \
+@interface YYSYNTH_DUMMY_CLASS_ ## _name_ : NSObject @end \
+@implementation YYSYNTH_DUMMY_CLASS_ ## _name_ @end
+#endif
+
+
+/**
+ Synthsize a dynamic object property in @implementation scope.
+ It allows us to add custom properties to existing classes in categories.
+ 
+ @param association  ASSIGN / RETAIN / COPY / RETAIN_NONATOMIC / COPY_NONATOMIC
+ @warning #import <objc/runtime.h>
+ *******************************************************************************
+ Example:
+     @interface NSObject (MyAdd)
+     @property (nonatomic, retain) UIColor *myColor;
+     @end
+     
+     #import <objc/runtime.h>
+     @implementation NSObject (MyAdd)
+     YYSYNTH_DYNAMIC_PROPERTY_OBJECT(myColor, setMyColor, RETAIN, UIColor *)
+     @end
+ */
+#ifndef YYSYNTH_DYNAMIC_PROPERTY_OBJECT
+#define YYSYNTH_DYNAMIC_PROPERTY_OBJECT(_getter_, _setter_, _association_, _type_) \
+- (void)_setter_ : (_type_)object { \
+    [self willChangeValueForKey:@#_getter_]; \
+    objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_ ## _association_); \
+    [self didChangeValueForKey:@#_getter_]; \
+} \
+- (_type_)_getter_ { \
+    return objc_getAssociatedObject(self, @selector(_setter_:)); \
+}
+#endif
+
+
+/**
+ Synthsize a dynamic c type property in @implementation scope.
+ It allows us to add custom properties to existing classes in categories.
+ 
+ @warning #import <objc/runtime.h>
+ *******************************************************************************
+ Example:
+     @interface NSObject (MyAdd)
+     @property (nonatomic, retain) CGPoint myPoint;
+     @end
+     
+     #import <objc/runtime.h>
+     @implementation NSObject (MyAdd)
+     YYSYNTH_DYNAMIC_PROPERTY_CTYPE(myPoint, setMyPoint, CGPoint)
+     @end
+ */
+#ifndef YYSYNTH_DYNAMIC_PROPERTY_CTYPE
+#define YYSYNTH_DYNAMIC_PROPERTY_CTYPE(_getter_, _setter_, _type_) \
+- (void)_setter_ : (_type_)object { \
+    [self willChangeValueForKey:@#_getter_]; \
+    NSValue *value = [NSValue value:&object withObjCType:@encode(_type_)]; \
+    objc_setAssociatedObject(self, _cmd, value, OBJC_ASSOCIATION_RETAIN); \
+    [self didChangeValueForKey:@#_getter_]; \
+} \
+- (_type_)_getter_ { \
+    _type_ cValue = { 0 }; \
+    NSValue *value = objc_getAssociatedObject(self, @selector(_setter_:)); \
+    [value getValue:&cValue]; \
+    return cValue; \
+}
+#endif
+
+/**
+ Synthsize a weak or strong reference.
+ 
+ Example:
+    @weakify(self)
+    [self doSomething^{
+        @strongify(self)
+        if (!self) return;
+        ...
+    }];
+
+ */
+#ifndef weakify
+    #if DEBUG
+        #if __has_feature(objc_arc)
+        #define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
+        #else
+        #define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
+        #endif
+    #else
+        #if __has_feature(objc_arc)
+        #define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
+        #else
+        #define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
+        #endif
+    #endif
+#endif
+
+#ifndef strongify
+    #if DEBUG
+        #if __has_feature(objc_arc)
+        #define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
+        #else
+        #define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
+        #endif
+    #else
+        #if __has_feature(objc_arc)
+        #define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
+        #else
+        #define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
+        #endif
+    #endif
+#endif
+
+
+/**
+ Convert CFRange to NSRange
+ @param range CFRange @return NSRange
+ */
+static inline NSRange YYNSRangeFromCFRange(CFRange range) {
+    return NSMakeRange(range.location, range.length);
+}
+
+/**
+ Convert NSRange to CFRange
+ @param range NSRange @return CFRange
+ */
+static inline CFRange YYCFRangeFromNSRange(NSRange range) {
+    return CFRangeMake(range.location, range.length);
+}
+
+/**
+ Same as CFAutorelease(), compatible for iOS6
+ @param arg CFObject @return same as input
+ */
+static inline CFTypeRef YYCFAutorelease(CFTypeRef CF_RELEASES_ARGUMENT arg) {
+    if (((long)CFAutorelease + 1) != 1) {
+        return CFAutorelease(arg);
+    } else {
+        id __autoreleasing obj = CFBridgingRelease(arg);
+        return (__bridge CFTypeRef)obj;
+    }
+}
+
+/**
+ Profile time cost.
+ @param ^block     code to benchmark
+ @param ^complete  code time cost (millisecond)
+ 
+ Usage:
+    YYBenchmark(^{
+        // code
+    }, ^(double ms) {
+        NSLog("time cost: %.2f ms",ms);
+    });
+ 
+ */
+static inline void YYBenchmark(void (^block)(void), void (^complete)(double ms)) {
+    // <QuartzCore/QuartzCore.h> version
+    /*
+    extern double CACurrentMediaTime (void);
+    double begin, end, ms;
+    begin = CACurrentMediaTime();
+    block();
+    end = CACurrentMediaTime();
+    ms = (end - begin) * 1000.0;
+    complete(ms);
+    */
+    
+    // <sys/time.h> version
+    struct timeval t0, t1;
+    gettimeofday(&t0, NULL);
+    block();
+    gettimeofday(&t1, NULL);
+    double ms = (double)(t1.tv_sec - t0.tv_sec) * 1e3 + (double)(t1.tv_usec - t0.tv_usec) * 1e-3;
+    complete(ms);
+}
+
+static inline NSDate *_YYCompileTime(const char *data, const char *time) {
+    NSString *timeStr = [NSString stringWithFormat:@"%s %s",data,time];
+    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
+    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
+    [formatter setDateFormat:@"MMM dd yyyy HH:mm:ss"];
+    [formatter setLocale:locale];
+    return [formatter dateFromString:timeStr];
+}
+
+/**
+ Get compile timestamp.
+ @return A new date object set to the compile date and time.
+ */
+#ifndef YYCompileTime
+// use macro to avoid compile warning when use pch file
+#define YYCompileTime() _YYCompileTime(__DATE__, __TIME__)
+#endif
+
+/**
+ Returns a dispatch_time delay from now.
+ */
+static inline dispatch_time_t dispatch_time_delay(NSTimeInterval second) {
+    return dispatch_time(DISPATCH_TIME_NOW, (int64_t)(second * NSEC_PER_SEC));
+}
+
+/**
+ Returns a dispatch_wall_time delay from now.
+ */
+static inline dispatch_time_t dispatch_walltime_delay(NSTimeInterval second) {
+    return dispatch_walltime(DISPATCH_TIME_NOW, (int64_t)(second * NSEC_PER_SEC));
+}
+
+/**
+ Returns a dispatch_wall_time from NSDate.
+ */
+static inline dispatch_time_t dispatch_walltime_date(NSDate *date) {
+    NSTimeInterval interval;
+    double second, subsecond;
+    struct timespec time;
+    dispatch_time_t milestone;
+    
+    interval = [date timeIntervalSince1970];
+    subsecond = modf(interval, &second);
+    time.tv_sec = second;
+    time.tv_nsec = subsecond * NSEC_PER_SEC;
+    milestone = dispatch_walltime(&time, 0);
+    return milestone;
+}
+
+/**
+ Whether in main queue/thread.
+ */
+static inline bool dispatch_is_main_queue() {
+    return pthread_main_np() != 0;
+}
+
+/**
+ Submits a block for asynchronous execution on a main queue and returns immediately.
+ */
+static inline void dispatch_async_on_main_queue(void (^block)()) {
+    if (pthread_main_np()) {
+        block();
+    } else {
+        dispatch_async(dispatch_get_main_queue(), block);
+    }
+}
+
+/**
+ Submits a block for execution on a main queue and waits until the block completes.
+ */
+static inline void dispatch_sync_on_main_queue(void (^block)()) {
+    if (pthread_main_np()) {
+        block();
+    } else {
+        dispatch_sync(dispatch_get_main_queue(), block);
+    }
+}
+
+/**
+ Initialize a pthread mutex.
+ */
+static inline void pthread_mutex_init_recursive(pthread_mutex_t *mutex, bool recursive) {
+#define YYMUTEX_ASSERT_ON_ERROR(x_) do { \
+__unused volatile int res = (x_); \
+assert(res == 0); \
+} while (0)
+    assert(mutex != NULL);
+    if (!recursive) {
+        YYMUTEX_ASSERT_ON_ERROR(pthread_mutex_init(mutex, NULL));
+    } else {
+        pthread_mutexattr_t attr;
+        YYMUTEX_ASSERT_ON_ERROR(pthread_mutexattr_init (&attr));
+        YYMUTEX_ASSERT_ON_ERROR(pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE));
+        YYMUTEX_ASSERT_ON_ERROR(pthread_mutex_init (mutex, &attr));
+        YYMUTEX_ASSERT_ON_ERROR(pthread_mutexattr_destroy (&attr));
+    }
+#undef YYMUTEX_ASSERT_ON_ERROR
+}
+
+
+YY_EXTERN_C_END
+#endif

+ 191 - 0
YYKit/Cache/YYCache.h

@@ -0,0 +1,191 @@
+//
+//  YYCache.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/13.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+@class YYMemoryCache, YYDiskCache;
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ `YYCache` is a thread safe key-value cache.
+ 
+ It use `YYMemoryCache` to store objects in a small and fast memory cache,
+ and use `YYDiskCache` to persisting objects to a large and slow disk cache.
+ See `YYMemoryCache` and `YYDiskCache` for more information.
+ */
+@interface YYCache : NSObject
+
+/** The name of the cache, readonly. */
+@property (copy, readonly) NSString *name;
+
+/** The underlying memory cache. see `YYMemoryCache` for more information.*/
+@property (strong, readonly) YYMemoryCache *memoryCache;
+
+/** The underlying disk cache. see `YYDiskCache` for more information.*/
+@property (strong, readonly) YYDiskCache *diskCache;
+
+/**
+ Create a new instance with the specified name.
+ Multiple instances with the same name will make the cache unstable.
+ 
+ @param name  The name of the cache. It will create a dictionary with the name in
+     the app's caches dictionary for disk cache. Once initialized you should not 
+     read and write to this directory.
+ @result A new cache object, or nil if an error occurs.
+ */
+- (nullable instancetype)initWithName:(NSString *)name;
+
+/**
+ Create a new instance with the specified path.
+ Multiple instances with the same name will make the cache unstable.
+ 
+ @param path  Full path of a directory in which the cache will write data.
+     Once initialized you should not read and write to this directory.
+ @result A new cache object, or nil if an error occurs.
+ */
+- (nullable instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER;
+
+/**
+ Convenience Initializers
+ Create a new instance with the specified name.
+ Multiple instances with the same name will make the cache unstable.
+ 
+ @param name  The name of the cache. It will create a dictionary with the name in
+     the app's caches dictionary for disk cache. Once initialized you should not 
+     read and write to this directory.
+ @result A new cache object, or nil if an error occurs.
+ */
++ (nullable instancetype)cacheWithName:(NSString *)name;
+
+/**
+ Convenience Initializers
+ Create a new instance with the specified path.
+ Multiple instances with the same name will make the cache unstable.
+ 
+ @param path  Full path of a directory in which the cache will write data.
+     Once initialized you should not read and write to this directory.
+ @result A new cache object, or nil if an error occurs.
+ */
++ (nullable instancetype)cacheWithPath:(NSString *)path;
+
+- (instancetype)init UNAVAILABLE_ATTRIBUTE;
++ (instancetype)new UNAVAILABLE_ATTRIBUTE;
+
+#pragma mark - Access Methods
+///=============================================================================
+/// @name Access Methods
+///=============================================================================
+
+/**
+ Returns a boolean value that indicates whether a given key is in cache.
+ This method may blocks the calling thread until file read finished.
+ 
+ @param key A string identifying the value. If nil, just return NO.
+ @return Whether the key is in cache.
+ */
+- (BOOL)containsObjectForKey:(NSString *)key;
+
+/**
+ Returns a boolean value with the block that indicates whether a given key is in cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param key   A string identifying the value. If nil, just return NO.
+ @param block A block which will be invoked in background queue when finished.
+ */
+- (void)containsObjectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key, BOOL contains))block;
+
+/**
+ Returns the value associated with a given key.
+ This method may blocks the calling thread until file read finished.
+ 
+ @param key A string identifying the value. If nil, just return nil.
+ @return The value associated with key, or nil if no value is associated with key.
+ */
+- (nullable id<NSCoding>)objectForKey:(NSString *)key;
+
+/**
+ Returns the value associated with a given key.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param key A string identifying the value. If nil, just return nil.
+ @param block A block which will be invoked in background queue when finished.
+ */
+- (void)objectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key, id<NSCoding> object))block;
+
+/**
+ Sets the value of the specified key in the cache.
+ This method may blocks the calling thread until file write finished.
+ 
+ @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
+ @param key    The key with which to associate the value. If nil, this method has no effect.
+ */
+- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key;
+
+/**
+ Sets the value of the specified key in the cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key withBlock:(nullable void(^)(void))block;
+
+/**
+ Removes the value of the specified key in the cache.
+ This method may blocks the calling thread until file delete finished.
+ 
+ @param key The key identifying the value to be removed. If nil, this method has no effect.
+ */
+- (void)removeObjectForKey:(NSString *)key;
+
+/**
+ Removes the value of the specified key in the cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param key The key identifying the value to be removed. If nil, this method has no effect.
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)removeObjectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key))block;
+
+/**
+ Empties the cache.
+ This method may blocks the calling thread until file delete finished.
+ */
+- (void)removeAllObjects;
+
+/**
+ Empties the cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)removeAllObjectsWithBlock:(void(^)(void))block;
+
+/**
+ Empties the cache with block.
+ This method returns immediately and executes the clear operation with block in background.
+ 
+ @warning You should not send message to this instance in these blocks.
+ @param progress This block will be invoked during removing, pass nil to ignore.
+ @param end      This block will be invoked at the end, pass nil to ignore.
+ */
+- (void)removeAllObjectsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
+                                 endBlock:(nullable void(^)(BOOL error))end;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 139 - 0
YYKit/Cache/YYCache.m

@@ -0,0 +1,139 @@
+//
+//  YYCache.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/13.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYCache.h"
+#import "YYMemoryCache.h"
+#import "YYDiskCache.h"
+
+@implementation YYCache
+
+- (instancetype) init {
+    NSLog(@"Use \"initWithName\" or \"initWithPath\" to create YYCache instance.");
+    return [self initWithPath:@""];
+}
+
+- (instancetype)initWithName:(NSString *)name {
+    if (name.length == 0) return nil;
+    NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
+    NSString *path = [cacheFolder stringByAppendingPathComponent:name];
+    return [self initWithPath:path];
+}
+
+- (instancetype)initWithPath:(NSString *)path {
+    if (path.length == 0) return nil;
+    YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:path];
+    if (!diskCache) return nil;
+    NSString *name = [path lastPathComponent];
+    YYMemoryCache *memoryCache = [YYMemoryCache new];
+    memoryCache.name = name;
+    
+    self = [super init];
+    _name = name;
+    _diskCache = diskCache;
+    _memoryCache = memoryCache;
+    return self;
+}
+
++ (instancetype)cacheWithName:(NSString *)name {
+	return [[self alloc] initWithName:name];
+}
+
++ (instancetype)cacheWithPath:(NSString *)path {
+    return [[self alloc] initWithPath:path];
+}
+
+- (BOOL)containsObjectForKey:(NSString *)key {
+    return [_memoryCache containsObjectForKey:key] || [_diskCache containsObjectForKey:key];
+}
+
+- (void)containsObjectForKey:(NSString *)key withBlock:(void (^)(NSString *key, BOOL contains))block {
+    if (!block) return;
+    
+    if ([_memoryCache containsObjectForKey:key]) {
+        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+            block(key, YES);
+        });
+    } else  {
+        [_diskCache containsObjectForKey:key withBlock:block];
+    }
+}
+
+- (id<NSCoding>)objectForKey:(NSString *)key {
+    id<NSCoding> object = [_memoryCache objectForKey:key];
+    if (!object) {
+        object = [_diskCache objectForKey:key];
+        if (object) {
+            [_memoryCache setObject:object forKey:key];
+        }
+    }
+    return object;
+}
+
+- (void)objectForKey:(NSString *)key withBlock:(void (^)(NSString *key, id<NSCoding> object))block {
+    if (!block) return;
+    id<NSCoding> object = [_memoryCache objectForKey:key];
+    if (object) {
+        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+            block(key, object);
+        });
+    } else {
+        [_diskCache objectForKey:key withBlock:^(NSString *key, id<NSCoding> object) {
+            if (object && ![_memoryCache objectForKey:key]) {
+                [_memoryCache setObject:object forKey:key];
+            }
+            block(key, object);
+        }];
+    }
+}
+
+- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key {
+    [_memoryCache setObject:object forKey:key];
+    [_diskCache setObject:object forKey:key];
+}
+
+- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key withBlock:(void (^)(void))block {
+    [_memoryCache setObject:object forKey:key];
+    [_diskCache setObject:object forKey:key withBlock:block];
+}
+
+- (void)removeObjectForKey:(NSString *)key {
+    [_memoryCache removeObjectForKey:key];
+    [_diskCache removeObjectForKey:key];
+}
+
+- (void)removeObjectForKey:(NSString *)key withBlock:(void (^)(NSString *key))block {
+    [_memoryCache removeObjectForKey:key];
+    [_diskCache removeObjectForKey:key withBlock:block];
+}
+
+- (void)removeAllObjects {
+    [_memoryCache removeAllObjects];
+    [_diskCache removeAllObjects];
+}
+
+- (void)removeAllObjectsWithBlock:(void(^)(void))block {
+    [_memoryCache removeAllObjects];
+    [_diskCache removeAllObjectsWithBlock:block];
+}
+
+- (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress
+                                 endBlock:(void(^)(BOOL error))end {
+    [_memoryCache removeAllObjects];
+    [_diskCache removeAllObjectsWithProgressBlock:progress endBlock:end];
+    
+}
+
+- (NSString *)description {
+    if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _name];
+    else return [NSString stringWithFormat:@"<%@: %p>", self.class, self];
+}
+
+@end

+ 412 - 0
YYKit/Cache/YYDiskCache.h

@@ -0,0 +1,412 @@
+//
+//  YYDiskCache.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ YYDiskCache is a thread-safe cache that stores key-value pairs backed by SQLite
+ and file system (similar to NSURLCache's disk cache).
+ 
+ YYDiskCache has these features:
+ 
+ * It use LRU (least-recently-used) to remove objects.
+ * It can be controlled by cost, count, and age.
+ * It can be configured to automatically evict objects when there's no free disk space.
+ * It can automatically decide the storage type (sqlite/file) for each object to get
+      better performance.
+ 
+ You may compile the latest version of sqlite and ignore the libsqlite3.dylib in
+ iOS system to get 2x~4x speed up.
+ */
+@interface YYDiskCache : NSObject
+
+#pragma mark - Attribute
+///=============================================================================
+/// @name Attribute
+///=============================================================================
+
+/** The name of the cache. Default is nil. */
+@property (nullable, copy) NSString *name;
+
+/** The path of the cache (read-only). */
+@property (readonly) NSString *path;
+
+/**
+ If the object's data size (in bytes) is larger than this value, then object will
+ be stored as a file, otherwise the object will be stored in sqlite.
+ 
+ 0 means all objects will be stored as separated files, NSUIntegerMax means all
+ objects will be stored in sqlite. 
+ 
+ The default value is 20480 (20KB).
+ */
+@property (readonly) NSUInteger inlineThreshold;
+
+/**
+ If this block is not nil, then the block will be used to archive object instead
+ of NSKeyedArchiver. You can use this block to support the objects which do not
+ conform to the `NSCoding` protocol.
+ 
+ The default value is nil.
+ */
+@property (nullable, copy) NSData *(^customArchiveBlock)(id object);
+
+/**
+ If this block is not nil, then the block will be used to unarchive object instead
+ of NSKeyedUnarchiver. You can use this block to support the objects which do not
+ conform to the `NSCoding` protocol.
+ 
+ The default value is nil.
+ */
+@property (nullable, copy) id (^customUnarchiveBlock)(NSData *data);
+
+/**
+ When an object needs to be saved as a file, this block will be invoked to generate
+ a file name for a specified key. If the block is nil, the cache use md5(key) as 
+ default file name.
+ 
+ The default value is nil.
+ */
+@property (nullable, copy) NSString *(^customFileNameBlock)(NSString *key);
+
+
+
+#pragma mark - Limit
+///=============================================================================
+/// @name Limit
+///=============================================================================
+
+/**
+ The maximum number of objects the cache should hold.
+ 
+ @discussion The default value is NSUIntegerMax, which means no limit.
+ This is not a strict limit — if the cache goes over the limit, some objects in the
+ cache could be evicted later in background queue.
+ */
+@property NSUInteger countLimit;
+
+/**
+ The maximum total cost that the cache can hold before it starts evicting objects.
+ 
+ @discussion The default value is NSUIntegerMax, which means no limit.
+ This is not a strict limit — if the cache goes over the limit, some objects in the
+ cache could be evicted later in background queue.
+ */
+@property NSUInteger costLimit;
+
+/**
+ The maximum expiry time of objects in cache.
+ 
+ @discussion The default value is DBL_MAX, which means no limit.
+ This is not a strict limit — if an object goes over the limit, the objects could
+ be evicted later in background queue.
+ */
+@property NSTimeInterval ageLimit;
+
+/**
+ The minimum free disk space (in bytes) which the cache should kept.
+ 
+ @discussion The default value is 0, which means no limit.
+ If the free disk space is lower than this value, the cache will remove objects
+ to free some disk space. This is not a strict limit—if the free disk space goes
+ over the limit, the objects could be evicted later in background queue.
+ */
+@property NSUInteger freeDiskSpaceLimit;
+
+/**
+ The auto trim check time interval in seconds. Default is 60 (1 minute).
+ 
+ @discussion The cache holds an internal timer to check whether the cache reaches
+ its limits, and if the limit is reached, it begins to evict objects.
+ */
+@property NSTimeInterval autoTrimInterval;
+
+/**
+ Set `YES` to enable error logs for debug.
+ */
+@property BOOL errorLogsEnabled;
+
+#pragma mark - Initializer
+///=============================================================================
+/// @name Initializer
+///=============================================================================
+- (instancetype)init UNAVAILABLE_ATTRIBUTE;
++ (instancetype)new UNAVAILABLE_ATTRIBUTE;
+
+/**
+ Create a new cache based on the specified path.
+ 
+ @param path Full path of a directory in which the cache will write data.
+     Once initialized you should not read and write to this directory.
+ 
+ @return A new cache object, or nil if an error occurs.
+ 
+ @warning If the cache instance for the specified path already exists in memory,
+     this method will return it directly, instead of creating a new instance.
+ */
+- (nullable instancetype)initWithPath:(NSString *)path;
+
+/**
+ The designated initializer.
+ 
+ @param path       Full path of a directory in which the cache will write data.
+     Once initialized you should not read and write to this directory.
+ 
+ @param threshold  The data store inline threshold in bytes. If the object's data
+     size (in bytes) is larger than this value, then object will be stored as a 
+     file, otherwise the object will be stored in sqlite. 0 means all objects will 
+     be stored as separated files, NSUIntegerMax means all objects will be stored 
+     in sqlite. If you don't know your object's size, 20480 is a good choice.
+     After first initialized you should not change this value of the specified path.
+ 
+ @return A new cache object, or nil if an error occurs.
+ 
+ @warning If the cache instance for the specified path already exists in memory,
+     this method will return it directly, instead of creating a new instance.
+ */
+- (nullable instancetype)initWithPath:(NSString *)path
+                      inlineThreshold:(NSUInteger)threshold NS_DESIGNATED_INITIALIZER;
+
+
+#pragma mark - Access Methods
+///=============================================================================
+/// @name Access Methods
+///=============================================================================
+
+/**
+ Returns a boolean value that indicates whether a given key is in cache.
+ This method may blocks the calling thread until file read finished.
+ 
+ @param key A string identifying the value. If nil, just return NO.
+ @return Whether the key is in cache.
+ */
+- (BOOL)containsObjectForKey:(NSString *)key;
+
+/**
+ Returns a boolean value with the block that indicates whether a given key is in cache.
+ This method returns immediately and invoke the passed block in background queue 
+ when the operation finished.
+ 
+ @param key   A string identifying the value. If nil, just return NO.
+ @param block A block which will be invoked in background queue when finished.
+ */
+- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block;
+
+/**
+ Returns the value associated with a given key.
+ This method may blocks the calling thread until file read finished.
+ 
+ @param key A string identifying the value. If nil, just return nil.
+ @return The value associated with key, or nil if no value is associated with key.
+ */
+- (nullable id<NSCoding>)objectForKey:(NSString *)key;
+
+/**
+ Returns the value associated with a given key.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param key A string identifying the value. If nil, just return nil.
+ @param block A block which will be invoked in background queue when finished.
+ */
+- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> _Nullable object))block;
+
+/**
+ Sets the value of the specified key in the cache.
+ This method may blocks the calling thread until file write finished.
+ 
+ @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
+ @param key    The key with which to associate the value. If nil, this method has no effect.
+ */
+- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key;
+
+/**
+ Sets the value of the specified key in the cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block;
+
+/**
+ Removes the value of the specified key in the cache.
+ This method may blocks the calling thread until file delete finished.
+ 
+ @param key The key identifying the value to be removed. If nil, this method has no effect.
+ */
+- (void)removeObjectForKey:(NSString *)key;
+
+/**
+ Removes the value of the specified key in the cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param key The key identifying the value to be removed. If nil, this method has no effect.
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block;
+
+/**
+ Empties the cache.
+ This method may blocks the calling thread until file delete finished.
+ */
+- (void)removeAllObjects;
+
+/**
+ Empties the cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)removeAllObjectsWithBlock:(void(^)(void))block;
+
+/**
+ Empties the cache with block.
+ This method returns immediately and executes the clear operation with block in background.
+ 
+ @warning You should not send message to this instance in these blocks.
+ @param progress This block will be invoked during removing, pass nil to ignore.
+ @param end      This block will be invoked at the end, pass nil to ignore.
+ */
+- (void)removeAllObjectsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
+                                 endBlock:(nullable void(^)(BOOL error))end;
+
+
+/**
+ Returns the number of objects in this cache.
+ This method may blocks the calling thread until file read finished.
+ 
+ @return The total objects count.
+ */
+- (NSInteger)totalCount;
+
+/**
+ Get the number of objects in this cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block;
+
+/**
+ Returns the total cost (in bytes) of objects in this cache.
+ This method may blocks the calling thread until file read finished.
+ 
+ @return The total objects cost in bytes.
+ */
+- (NSInteger)totalCost;
+
+/**
+ Get the total cost (in bytes) of objects in this cache.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block;
+
+
+#pragma mark - Trim
+///=============================================================================
+/// @name Trim
+///=============================================================================
+
+/**
+ Removes objects from the cache use LRU, until the `totalCount` is below the specified value.
+ This method may blocks the calling thread until operation finished.
+ 
+ @param count  The total count allowed to remain after the cache has been trimmed.
+ */
+- (void)trimToCount:(NSUInteger)count;
+
+/**
+ Removes objects from the cache use LRU, until the `totalCount` is below the specified value.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param count  The total count allowed to remain after the cache has been trimmed.
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block;
+
+/**
+ Removes objects from the cache use LRU, until the `totalCost` is below the specified value.
+ This method may blocks the calling thread until operation finished.
+ 
+ @param cost The total cost allowed to remain after the cache has been trimmed.
+ */
+- (void)trimToCost:(NSUInteger)cost;
+
+/**
+ Removes objects from the cache use LRU, until the `totalCost` is below the specified value.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param cost The total cost allowed to remain after the cache has been trimmed.
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block;
+
+/**
+ Removes objects from the cache use LRU, until all expiry objects removed by the specified value.
+ This method may blocks the calling thread until operation finished.
+ 
+ @param age  The maximum age of the object.
+ */
+- (void)trimToAge:(NSTimeInterval)age;
+
+/**
+ Removes objects from the cache use LRU, until all expiry objects removed by the specified value.
+ This method returns immediately and invoke the passed block in background queue
+ when the operation finished.
+ 
+ @param age  The maximum age of the object.
+ @param block  A block which will be invoked in background queue when finished.
+ */
+- (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block;
+
+
+#pragma mark - Extended Data
+///=============================================================================
+/// @name Extended Data
+///=============================================================================
+
+/**
+ Get extended data from an object.
+ 
+ @discussion See 'setExtendedData:toObject:' for more information.
+ 
+ @param object An object.
+ @return The extended data.
+ */
++ (nullable NSData *)getExtendedDataFromObject:(id)object;
+
+/**
+ Set extended data to an object.
+ 
+ @discussion You can set any extended data to an object before you save the object
+ to disk cache. The extended data will also be saved with this object. You can get
+ the extended data later with "getExtendedDataFromObject:".
+ 
+ @param extendedData The extended data (pass nil to remove).
+ @param object       The object.
+ */
++ (void)setExtendedData:(nullable NSData *)extendedData toObject:(id)object;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 444 - 0
YYKit/Cache/YYDiskCache.m

@@ -0,0 +1,444 @@
+//
+//  YYDiskCache.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/11.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYDiskCache.h"
+#import "YYKVStorage.h"
+#import "NSString+YYAdd.h"
+#import "UIDevice+YYAdd.h"
+#import <objc/runtime.h>
+#import <time.h>
+
+#define Lock() dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER)
+#define Unlock() dispatch_semaphore_signal(self->_lock)
+
+static const int extended_data_key;
+
+/// Free disk space in bytes.
+static int64_t _YYDiskSpaceFree() {
+    NSError *error = nil;
+    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
+    if (error) return -1;
+    int64_t space =  [[attrs objectForKey:NSFileSystemFreeSize] longLongValue];
+    if (space < 0) space = -1;
+    return space;
+}
+
+
+/// weak reference for all instances
+static NSMapTable *_globalInstances;
+static dispatch_semaphore_t _globalInstancesLock;
+
+static void _YYDiskCacheInitGlobal() {
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _globalInstancesLock = dispatch_semaphore_create(1);
+        _globalInstances = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
+    });
+}
+
+static YYDiskCache *_YYDiskCacheGetGlobal(NSString *path) {
+    if (path.length == 0) return nil;
+    _YYDiskCacheInitGlobal();
+    dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
+    id cache = [_globalInstances objectForKey:path];
+    dispatch_semaphore_signal(_globalInstancesLock);
+    return cache;
+}
+
+static void _YYDiskCacheSetGlobal(YYDiskCache *cache) {
+    if (cache.path.length == 0) return;
+    _YYDiskCacheInitGlobal();
+    dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
+    [_globalInstances setObject:cache forKey:cache.path];
+    dispatch_semaphore_signal(_globalInstancesLock);
+}
+
+
+
+@implementation YYDiskCache {
+    YYKVStorage *_kv;
+    dispatch_semaphore_t _lock;
+    dispatch_queue_t _queue;
+}
+
+- (void)_trimRecursively {
+    __weak typeof(self) _self = self;
+    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_autoTrimInterval * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
+        __strong typeof(_self) self = _self;
+        if (!self) return;
+        [self _trimInBackground];
+        [self _trimRecursively];
+    });
+}
+
+- (void)_trimInBackground {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        if (!self) return;
+        Lock();
+        [self _trimToCost:self.costLimit];
+        [self _trimToCount:self.countLimit];
+        [self _trimToAge:self.ageLimit];
+        [self _trimToFreeDiskSpace:self.freeDiskSpaceLimit];
+        Unlock();
+    });
+}
+
+- (void)_trimToCost:(NSUInteger)costLimit {
+    if (costLimit >= INT_MAX) return;
+    [_kv removeItemsToFitSize:(int)costLimit];
+    
+}
+
+- (void)_trimToCount:(NSUInteger)countLimit {
+    if (countLimit >= INT_MAX) return;
+    [_kv removeItemsToFitCount:(int)countLimit];
+}
+
+- (void)_trimToAge:(NSTimeInterval)ageLimit {
+    if (ageLimit <= 0) {
+        [_kv removeAllItems];
+        return;
+    }
+    long timestamp = time(NULL);
+    if (timestamp <= ageLimit) return;
+    long age = timestamp - ageLimit;
+    if (age >= INT_MAX) return;
+    [_kv removeItemsEarlierThanTime:(int)age];
+}
+
+- (void)_trimToFreeDiskSpace:(NSUInteger)targetFreeDiskSpace {
+    if (targetFreeDiskSpace == 0) return;
+    int64_t totalBytes = [_kv getItemsSize];
+    if (totalBytes <= 0) return;
+    int64_t diskFreeBytes = _YYDiskSpaceFree();
+    if (diskFreeBytes < 0) return;
+    int64_t needTrimBytes = targetFreeDiskSpace - diskFreeBytes;
+    if (needTrimBytes <= 0) return;
+    int64_t costLimit = totalBytes - needTrimBytes;
+    if (costLimit < 0) costLimit = 0;
+    [self _trimToCost:(int)costLimit];
+}
+
+- (NSString *)_filenameForKey:(NSString *)key {
+    NSString *filename = nil;
+    if (_customFileNameBlock) filename = _customFileNameBlock(key);
+    if (!filename) filename = key.md5String;
+    return filename;
+}
+
+- (void)_appWillBeTerminated {
+    Lock();
+    _kv = nil;
+    Unlock();
+}
+
+#pragma mark - public
+
+- (void)dealloc {
+    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
+}
+
+- (instancetype)init {
+    @throw [NSException exceptionWithName:@"YYDiskCache init error" reason:@"YYDiskCache must be initialized with a path. Use 'initWithPath:' or 'initWithPath:inlineThreshold:' instead." userInfo:nil];
+    return [self initWithPath:@"" inlineThreshold:0];
+}
+
+- (instancetype)initWithPath:(NSString *)path {
+    return [self initWithPath:path inlineThreshold:1024 * 20]; // 20KB
+}
+
+- (instancetype)initWithPath:(NSString *)path
+             inlineThreshold:(NSUInteger)threshold {
+    self = [super init];
+    if (!self) return nil;
+    
+    YYDiskCache *globalCache = _YYDiskCacheGetGlobal(path);
+    if (globalCache) return globalCache;
+    
+    YYKVStorageType type;
+    if (threshold == 0) {
+        type = YYKVStorageTypeFile;
+    } else if (threshold == NSUIntegerMax) {
+        type = YYKVStorageTypeSQLite;
+    } else {
+        type = YYKVStorageTypeMixed;
+    }
+    
+    YYKVStorage *kv = [[YYKVStorage alloc] initWithPath:path type:type];
+    if (!kv) return nil;
+    
+    _kv = kv;
+    _path = path;
+    _lock = dispatch_semaphore_create(1);
+    _queue = dispatch_queue_create("com.ibireme.cache.disk", DISPATCH_QUEUE_CONCURRENT);
+    _inlineThreshold = threshold;
+    _countLimit = NSUIntegerMax;
+    _costLimit = NSUIntegerMax;
+    _ageLimit = DBL_MAX;
+    _freeDiskSpaceLimit = 0;
+    _autoTrimInterval = 60;
+    
+    [self _trimRecursively];
+    _YYDiskCacheSetGlobal(self);
+    
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appWillBeTerminated) name:UIApplicationWillTerminateNotification object:nil];
+    return self;
+}
+
+- (BOOL)containsObjectForKey:(NSString *)key {
+    if (!key) return NO;
+    Lock();
+    BOOL contains = [_kv itemExistsForKey:key];
+    Unlock();
+    return contains;
+}
+
+- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block {
+    if (!block) return;
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        BOOL contains = [self containsObjectForKey:key];
+        block(key, contains);
+    });
+}
+
+- (id<NSCoding>)objectForKey:(NSString *)key {
+    if (!key) return nil;
+    Lock();
+    YYKVStorageItem *item = [_kv getItemForKey:key];
+    Unlock();
+    if (!item.value) return nil;
+    
+    id object = nil;
+    if (_customUnarchiveBlock) {
+        object = _customUnarchiveBlock(item.value);
+    } else {
+        @try {
+            object = [NSKeyedUnarchiver unarchiveObjectWithData:item.value];
+        }
+        @catch (NSException *exception) {
+            // nothing to do...
+        }
+    }
+    if (object && item.extendedData) {
+        [YYDiskCache setExtendedData:item.extendedData toObject:object];
+    }
+    return object;
+}
+
+- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> object))block {
+    if (!block) return;
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        id<NSCoding> object = [self objectForKey:key];
+        block(key, object);
+    });
+}
+
+- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key {
+    if (!key) return;
+    if (!object) {
+        [self removeObjectForKey:key];
+        return;
+    }
+    
+    NSData *extendedData = [YYDiskCache getExtendedDataFromObject:object];
+    NSData *value = nil;
+    if (_customArchiveBlock) {
+        value = _customArchiveBlock(object);
+    } else {
+        @try {
+            value = [NSKeyedArchiver archivedDataWithRootObject:object];
+        }
+        @catch (NSException *exception) {
+            // nothing to do...
+        }
+    }
+    if (!value) return;
+    NSString *filename = nil;
+    if (_kv.type != YYKVStorageTypeSQLite) {
+        if (value.length > _inlineThreshold) {
+            filename = [self _filenameForKey:key];
+        }
+    }
+    
+    Lock();
+    [_kv saveItemWithKey:key value:value filename:filename extendedData:extendedData];
+    Unlock();
+}
+
+- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        [self setObject:object forKey:key];
+        if (block) block();
+    });
+}
+
+- (void)removeObjectForKey:(NSString *)key {
+    if (!key) return;
+    Lock();
+    [_kv removeItemForKey:key];
+    Unlock();
+}
+
+- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        [self removeObjectForKey:key];
+        if (block) block(key);
+    });
+}
+
+- (void)removeAllObjects {
+    Lock();
+    [_kv removeAllItems];
+    Unlock();
+}
+
+- (void)removeAllObjectsWithBlock:(void(^)(void))block {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        [self removeAllObjects];
+        if (block) block();
+    });
+}
+
+- (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress
+                                 endBlock:(void(^)(BOOL error))end {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        if (!self) {
+            if (end) end(YES);
+            return;
+        }
+        Lock();
+        [_kv removeAllItemsWithProgressBlock:progress endBlock:end];
+        Unlock();
+    });
+}
+
+- (NSInteger)totalCount {
+    Lock();
+    int count = [_kv getItemsCount];
+    Unlock();
+    return count;
+}
+
+- (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block {
+    if (!block) return;
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        NSInteger totalCount = [self totalCount];
+        block(totalCount);
+    });
+}
+
+- (NSInteger)totalCost {
+    Lock();
+    int count = [_kv getItemsSize];
+    Unlock();
+    return count;
+}
+
+- (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block {
+    if (!block) return;
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        NSInteger totalCost = [self totalCost];
+        block(totalCost);
+    });
+}
+
+- (void)trimToCount:(NSUInteger)count {
+    Lock();
+    [self _trimToCount:count];
+    Unlock();
+}
+
+- (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        [self trimToCount:count];
+        if (block) block();
+    });
+}
+
+- (void)trimToCost:(NSUInteger)cost {
+    Lock();
+    [self _trimToCost:cost];
+    Unlock();
+}
+
+- (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        [self trimToCost:cost];
+        if (block) block();
+    });
+}
+
+- (void)trimToAge:(NSTimeInterval)age {
+    Lock();
+    [self _trimToAge:age];
+    Unlock();
+}
+
+- (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block {
+    __weak typeof(self) _self = self;
+    dispatch_async(_queue, ^{
+        __strong typeof(_self) self = _self;
+        [self trimToAge:age];
+        if (block) block();
+    });
+}
+
++ (NSData *)getExtendedDataFromObject:(id)object {
+    if (!object) return nil;
+    return (NSData *)objc_getAssociatedObject(object, &extended_data_key);
+}
+
++ (void)setExtendedData:(NSData *)extendedData toObject:(id)object {
+    if (!object) return;
+    objc_setAssociatedObject(object, &extended_data_key, extendedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (NSString *)description {
+    if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@:%@)", self.class, self, _name, _path];
+    else return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _path];
+}
+
+- (BOOL)errorLogsEnabled {
+    Lock();
+    BOOL enabled = _kv.errorLogsEnabled;
+    Unlock();
+    return enabled;
+}
+
+- (void)setErrorLogsEnabled:(BOOL)errorLogsEnabled {
+    Lock();
+    _kv.errorLogsEnabled = errorLogsEnabled;
+    Unlock();
+}
+
+@end

+ 325 - 0
YYKit/Cache/YYKVStorage.h

@@ -0,0 +1,325 @@
+//
+//  YYKVStorage.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/4/22.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ YYKVStorageItem is used by `YYKVStorage` to store key-value pair and meta data.
+ Typically, you should not use this class directly.
+ */
+@interface YYKVStorageItem : NSObject
+@property (nonatomic, strong) NSString *key;                ///< key
+@property (nonatomic, strong) NSData *value;                ///< value
+@property (nullable, nonatomic, strong) NSString *filename; ///< filename (nil if inline)
+@property (nonatomic) int size;                             ///< value's size in bytes
+@property (nonatomic) int modTime;                          ///< modification unix timestamp
+@property (nonatomic) int accessTime;                       ///< last access unix timestamp
+@property (nullable, nonatomic, strong) NSData *extendedData; ///< extended data (nil if no extended data)
+@end
+
+/**
+ Storage type, indicated where the `YYKVStorageItem.value` stored.
+ 
+ @discussion Typically, write data to sqlite is faster than extern file, but 
+ reading performance is dependent on data size. In my test (on iPhone 6 64G), 
+ read data from extern file is faster than from sqlite when the data is larger 
+ than 20KB.
+ 
+ * If you want to store large number of small datas (such as contacts cache), 
+   use YYKVStorageTypeSQLite to get better performance.
+ * If you want to store large files (such as image cache),
+   use YYKVStorageTypeFile to get better performance.
+ * You can use YYKVStorageTypeMixed and choice your storage type for each item.
+ 
+ See <http://www.sqlite.org/intern-v-extern-blob.html> for more information.
+ */
+typedef NS_ENUM(NSUInteger, YYKVStorageType) {
+    
+    /// The `value` is stored as a file in file system.
+    YYKVStorageTypeFile = 0,
+    
+    /// The `value` is stored in sqlite with blob type.
+    YYKVStorageTypeSQLite = 1,
+    
+    /// The `value` is stored in file system or sqlite based on your choice.
+    YYKVStorageTypeMixed = 2,
+};
+
+
+
+/**
+ YYKVStorage is a key-value storage based on sqlite and file system.
+ Typically, you should not use this class directly.
+ 
+ @discussion The designated initializer for YYKVStorage is `initWithPath:type:`. 
+ After initialized, a directory is created based on the `path` to hold key-value data.
+ Once initialized you should not read or write this directory without the instance.
+ 
+ You may compile the latest version of sqlite and ignore the libsqlite3.dylib in
+ iOS system to get 2x~4x speed up.
+ 
+ @warning The instance of this class is *NOT* thread safe, you need to make sure 
+ that there's only one thread to access the instance at the same time. If you really 
+ need to process large amounts of data in multi-thread, you should split the data
+ to multiple KVStorage instance (sharding).
+ */
+@interface YYKVStorage : NSObject
+
+#pragma mark - Attribute
+///=============================================================================
+/// @name Attribute
+///=============================================================================
+
+@property (nonatomic, readonly) NSString *path;        ///< The path of this storage.
+@property (nonatomic, readonly) YYKVStorageType type;  ///< The type of this storage.
+@property (nonatomic) BOOL errorLogsEnabled;           ///< Set `YES` to enable error logs for debug.
+
+#pragma mark - Initializer
+///=============================================================================
+/// @name Initializer
+///=============================================================================
+- (instancetype)init UNAVAILABLE_ATTRIBUTE;
++ (instancetype)new UNAVAILABLE_ATTRIBUTE;
+
+/**
+ The designated initializer. 
+ 
+ @param path  Full path of a directory in which the storage will write data. If
+    the directory is not exists, it will try to create one, otherwise it will 
+    read the data in this directory.
+ @param type  The storage type. After first initialized you should not change the 
+    type of the specified path.
+ @return  A new storage object, or nil if an error occurs.
+ @warning Multiple instances with the same path will make the storage unstable.
+ */
+- (nullable instancetype)initWithPath:(NSString *)path type:(YYKVStorageType)type NS_DESIGNATED_INITIALIZER;
+
+
+#pragma mark - Save Items
+///=============================================================================
+/// @name Save Items
+///=============================================================================
+
+/**
+ Save an item or update the item with 'key' if it already exists.
+ 
+ @discussion This method will save the item.key, item.value, item.filename and
+ item.extendedData to disk or sqlite, other properties will be ignored. item.key 
+ and item.value should not be empty (nil or zero length).
+ 
+ If the `type` is YYKVStorageTypeFile, then the item.filename should not be empty.
+ If the `type` is YYKVStorageTypeSQLite, then the item.filename will be ignored.
+ It the `type` is YYKVStorageTypeMixed, then the item.value will be saved to file 
+ system if the item.filename is not empty, otherwise it will be saved to sqlite.
+ 
+ @param item  An item.
+ @return Whether succeed.
+ */
+- (BOOL)saveItem:(YYKVStorageItem *)item;
+
+/**
+ Save an item or update the item with 'key' if it already exists.
+ 
+ @discussion This method will save the key-value pair to sqlite. If the `type` is
+ YYKVStorageTypeFile, then this method will failed.
+ 
+ @param key   The key, should not be empty (nil or zero length).
+ @param value The key, should not be empty (nil or zero length).
+ @return Whether succeed.
+ */
+- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value;
+
+/**
+ Save an item or update the item with 'key' if it already exists.
+ 
+ @discussion
+ If the `type` is YYKVStorageTypeFile, then the `filename` should not be empty.
+ If the `type` is YYKVStorageTypeSQLite, then the `filename` will be ignored.
+ It the `type` is YYKVStorageTypeMixed, then the `value` will be saved to file
+ system if the `filename` is not empty, otherwise it will be saved to sqlite.
+ 
+ @param key           The key, should not be empty (nil or zero length).
+ @param value         The key, should not be empty (nil or zero length).
+ @param filename      The filename.
+ @param extendedData  The extended data for this item (pass nil to ignore it).
+ 
+ @return Whether succeed.
+ */
+- (BOOL)saveItemWithKey:(NSString *)key
+                  value:(NSData *)value
+               filename:(nullable NSString *)filename
+           extendedData:(nullable NSData *)extendedData;
+
+#pragma mark - Remove Items
+///=============================================================================
+/// @name Remove Items
+///=============================================================================
+
+/**
+ Remove an item with 'key'.
+ 
+ @param key The item's key.
+ @return Whether succeed.
+ */
+- (BOOL)removeItemForKey:(NSString *)key;
+
+/**
+ Remove items with an array of keys.
+ 
+ @param keys An array of specified keys.
+ 
+ @return Whether succeed.
+ */
+- (BOOL)removeItemForKeys:(NSArray<NSString *> *)keys;
+
+/**
+ Remove all items which `value` is larger than a specified size.
+ 
+ @param size  The maximum size in bytes.
+ @return Whether succeed.
+ */
+- (BOOL)removeItemsLargerThanSize:(int)size;
+
+/**
+ Remove all items which last access time is earlier than a specified timestamp.
+ 
+ @param time  The specified unix timestamp.
+ @return Whether succeed.
+ */
+- (BOOL)removeItemsEarlierThanTime:(int)time;
+
+/**
+ Remove items to make the total size not larger than a specified size.
+ The least recently used (LRU) items will be removed first.
+ 
+ @param maxSize The specified size in bytes.
+ @return Whether succeed.
+ */
+- (BOOL)removeItemsToFitSize:(int)maxSize;
+
+/**
+ Remove items to make the total count not larger than a specified count.
+ The least recently used (LRU) items will be removed first.
+ 
+ @param maxCount The specified item count.
+ @return Whether succeed.
+ */
+- (BOOL)removeItemsToFitCount:(int)maxCount;
+
+/**
+ Remove all items in background queue.
+ 
+ @discussion This method will remove the files and sqlite database to a trash
+ folder, and then clear the folder in background queue. So this method is much 
+ faster than `removeAllItemsWithProgressBlock:endBlock:`.
+ 
+ @return Whether succeed.
+ */
+- (BOOL)removeAllItems;
+
+/**
+ Remove all items.
+ 
+ @warning You should not send message to this instance in these blocks.
+ @param progress This block will be invoked during removing, pass nil to ignore.
+ @param end      This block will be invoked at the end, pass nil to ignore.
+ */
+- (void)removeAllItemsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
+                               endBlock:(nullable void(^)(BOOL error))end;
+
+
+#pragma mark - Get Items
+///=============================================================================
+/// @name Get Items
+///=============================================================================
+
+/**
+ Get item with a specified key.
+ 
+ @param key A specified key.
+ @return Item for the key, or nil if not exists / error occurs.
+ */
+- (nullable YYKVStorageItem *)getItemForKey:(NSString *)key;
+
+/**
+ Get item information with a specified key.
+ The `value` in this item will be ignored.
+ 
+ @param key A specified key.
+ @return Item information for the key, or nil if not exists / error occurs.
+ */
+- (nullable YYKVStorageItem *)getItemInfoForKey:(NSString *)key;
+
+/**
+ Get item value with a specified key.
+ 
+ @param key  A specified key.
+ @return Item's value, or nil if not exists / error occurs.
+ */
+- (nullable NSData *)getItemValueForKey:(NSString *)key;
+
+/**
+ Get items with an array of keys.
+ 
+ @param keys  An array of specified keys.
+ @return An array of `YYKVStorageItem`, or nil if not exists / error occurs.
+ */
+- (nullable NSArray<YYKVStorageItem *> *)getItemForKeys:(NSArray<NSString *> *)keys;
+
+/**
+ Get item infomartions with an array of keys.
+ The `value` in items will be ignored.
+ 
+ @param keys  An array of specified keys.
+ @return An array of `YYKVStorageItem`, or nil if not exists / error occurs.
+ */
+- (nullable NSArray<YYKVStorageItem *> *)getItemInfoForKeys:(NSArray<NSString *> *)keys;
+
+/**
+ Get items value with an array of keys.
+ 
+ @param keys  An array of specified keys.
+ @return A dictionary which key is 'key' and value is 'value', or nil if not 
+    exists / error occurs.
+ */
+- (nullable NSDictionary<NSString *, NSData *> *)getItemValueForKeys:(NSArray<NSString *> *)keys;
+
+#pragma mark - Get Storage Status
+///=============================================================================
+/// @name Get Storage Status
+///=============================================================================
+
+/**
+ Whether an item exists for a specified key.
+ 
+ @param key  A specified key.
+ 
+ @return `YES` if there's an item exists for the key, `NO` if not exists or an error occurs.
+ */
+- (BOOL)itemExistsForKey:(NSString *)key;
+
+/**
+ Get total item count.
+ @return Total item count, -1 when an error occurs.
+ */
+- (int)getItemsCount;
+
+/**
+ Get item value's total size in bytes.
+ @return Total size in bytes, -1 when an error occurs.
+ */
+- (int)getItemsSize;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 1053 - 0
YYKit/Cache/YYKVStorage.m

@@ -0,0 +1,1053 @@
+//
+//  YYKVStorage.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/4/22.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYKVStorage.h"
+#import "UIApplication+YYAdd.h"
+#import <UIKit/UIKit.h>
+#import <time.h>
+
+#if __has_include(<sqlite3.h>)
+#import <sqlite3.h>
+#else
+#import "sqlite3.h"
+#endif
+
+
+static const NSUInteger kMaxErrorRetryCount = 8;
+static const NSTimeInterval kMinRetryTimeInterval = 2.0;
+static const int kPathLengthMax = PATH_MAX - 64;
+static NSString *const kDBFileName = @"manifest.sqlite";
+static NSString *const kDBShmFileName = @"manifest.sqlite-shm";
+static NSString *const kDBWalFileName = @"manifest.sqlite-wal";
+static NSString *const kDataDirectoryName = @"data";
+static NSString *const kTrashDirectoryName = @"trash";
+
+/*
+ File:
+ /path/
+      /manifest.sqlite
+      /manifest.sqlite-shm
+      /manifest.sqlite-wal
+      /data/
+           /e10adc3949ba59abbe56e057f20f883e
+           /e10adc3949ba59abbe56e057f20f883e
+      /trash/
+            /unused_file_or_folder
+ 
+ SQL:
+ create table if not exists manifest (
+    key                 text,
+    filename            text,
+    size                integer,
+    inline_data         blob,
+    modification_time   integer,
+    last_access_time    integer,
+    extended_data       blob,
+    primary key(key)
+ ); 
+ create index if not exists last_access_time_idx on manifest(last_access_time);
+ */
+
+@implementation YYKVStorageItem
+@end
+
+@implementation YYKVStorage {
+    dispatch_queue_t _trashQueue;
+    
+    NSString *_path;
+    NSString *_dbPath;
+    NSString *_dataPath;
+    NSString *_trashPath;
+    
+    sqlite3 *_db;
+    CFMutableDictionaryRef _dbStmtCache;
+    NSTimeInterval _dbLastOpenErrorTime;
+    NSUInteger _dbOpenErrorCount;
+}
+
+
+#pragma mark - db
+
+- (BOOL)_dbOpen {
+    if (_db) return YES;
+    
+    int result = sqlite3_open(_dbPath.UTF8String, &_db);
+    if (result == SQLITE_OK) {
+        CFDictionaryKeyCallBacks keyCallbacks = kCFCopyStringDictionaryKeyCallBacks;
+        CFDictionaryValueCallBacks valueCallbacks = {0};
+        _dbStmtCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &keyCallbacks, &valueCallbacks);
+        _dbLastOpenErrorTime = 0;
+        _dbOpenErrorCount = 0;
+        return YES;
+    } else {
+        _db = NULL;
+        if (_dbStmtCache) CFRelease(_dbStmtCache);
+        _dbStmtCache = NULL;
+        _dbLastOpenErrorTime = CACurrentMediaTime();
+        _dbOpenErrorCount++;
+        
+        if (_errorLogsEnabled) {
+            NSLog(@"%s line:%d sqlite open failed (%d).", __FUNCTION__, __LINE__, result);
+        }
+        return NO;
+    }
+}
+
+- (BOOL)_dbClose {
+    if (!_db) return YES;
+    
+    int  result = 0;
+    BOOL retry = NO;
+    BOOL stmtFinalized = NO;
+    
+    if (_dbStmtCache) CFRelease(_dbStmtCache);
+    _dbStmtCache = NULL;
+    
+    do {
+        retry = NO;
+        result = sqlite3_close(_db);
+        if (result == SQLITE_BUSY || result == SQLITE_LOCKED) {
+            if (!stmtFinalized) {
+                stmtFinalized = YES;
+                sqlite3_stmt *stmt;
+                while ((stmt = sqlite3_next_stmt(_db, nil)) != 0) {
+                    sqlite3_finalize(stmt);
+                    retry = YES;
+                }
+            }
+        } else if (result != SQLITE_OK) {
+            if (_errorLogsEnabled) {
+                NSLog(@"%s line:%d sqlite close failed (%d).", __FUNCTION__, __LINE__, result);
+            }
+        }
+    } while (retry);
+    _db = NULL;
+    return YES;
+}
+
+- (BOOL)_dbCheck {
+    if (!_db) {
+        if (_dbOpenErrorCount < kMaxErrorRetryCount &&
+            CACurrentMediaTime() - _dbLastOpenErrorTime > kMinRetryTimeInterval) {
+            return [self _dbOpen] && [self _dbInitialize];
+        } else {
+            return NO;
+        }
+    }
+    return YES;
+}
+
+- (BOOL)_dbInitialize {
+    NSString *sql = @"pragma journal_mode = wal; pragma synchronous = normal; create table if not exists manifest (key text, filename text, size integer, inline_data blob, modification_time integer, last_access_time integer, extended_data blob, primary key(key)); create index if not exists last_access_time_idx on manifest(last_access_time);";
+    return [self _dbExecute:sql];
+}
+
+- (void)_dbCheckpoint {
+    if (![self _dbCheck]) return;
+    // Cause a checkpoint to occur, merge `sqlite-wal` file to `sqlite` file.
+    sqlite3_wal_checkpoint(_db, NULL);
+}
+
+- (BOOL)_dbExecute:(NSString *)sql {
+    if (sql.length == 0) return NO;
+    if (![self _dbCheck]) return NO;
+    
+    char *error = NULL;
+    int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &error);
+    if (error) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite exec error (%d): %s", __FUNCTION__, __LINE__, result, error);
+        sqlite3_free(error);
+    }
+    
+    return result == SQLITE_OK;
+}
+
+- (sqlite3_stmt *)_dbPrepareStmt:(NSString *)sql {
+    if (![self _dbCheck] || sql.length == 0 || !_dbStmtCache) return NULL;
+    sqlite3_stmt *stmt = (sqlite3_stmt *)CFDictionaryGetValue(_dbStmtCache, (__bridge const void *)(sql));
+    if (!stmt) {
+        int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
+        if (result != SQLITE_OK) {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+            return NULL;
+        }
+        CFDictionarySetValue(_dbStmtCache, (__bridge const void *)(sql), stmt);
+    } else {
+        sqlite3_reset(stmt);
+    }
+    return stmt;
+}
+
+- (NSString *)_dbJoinedKeys:(NSArray *)keys {
+    NSMutableString *string = [NSMutableString new];
+    for (NSUInteger i = 0,max = keys.count; i < max; i++) {
+        [string appendString:@"?"];
+        if (i + 1 != max) {
+            [string appendString:@","];
+        }
+    }
+    return string;
+}
+
+- (void)_dbBindJoinedKeys:(NSArray *)keys stmt:(sqlite3_stmt *)stmt fromIndex:(int)index{
+    for (int i = 0, max = (int)keys.count; i < max; i++) {
+        NSString *key = keys[i];
+        sqlite3_bind_text(stmt, index + i, key.UTF8String, -1, NULL);
+    }
+}
+
+- (BOOL)_dbSaveWithKey:(NSString *)key value:(NSData *)value fileName:(NSString *)fileName extendedData:(NSData *)extendedData {
+    NSString *sql = @"insert or replace into manifest (key, filename, size, inline_data, modification_time, last_access_time, extended_data) values (?1, ?2, ?3, ?4, ?5, ?6, ?7);";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return NO;
+    
+    int timestamp = (int)time(NULL);
+    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
+    sqlite3_bind_text(stmt, 2, fileName.UTF8String, -1, NULL);
+    sqlite3_bind_int(stmt, 3, (int)value.length);
+    if (fileName.length == 0) {
+        sqlite3_bind_blob(stmt, 4, value.bytes, (int)value.length, 0);
+    } else {
+        sqlite3_bind_blob(stmt, 4, NULL, 0, 0);
+    }
+    sqlite3_bind_int(stmt, 5, timestamp);
+    sqlite3_bind_int(stmt, 6, timestamp);
+    sqlite3_bind_blob(stmt, 7, extendedData.bytes, (int)extendedData.length, 0);
+    
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_DONE) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite insert error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    return YES;
+}
+
+- (BOOL)_dbUpdateAccessTimeWithKey:(NSString *)key {
+    NSString *sql = @"update manifest set last_access_time = ?1 where key = ?2;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return NO;
+    sqlite3_bind_int(stmt, 1, (int)time(NULL));
+    sqlite3_bind_text(stmt, 2, key.UTF8String, -1, NULL);
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_DONE) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite update error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    return YES;
+}
+
+- (BOOL)_dbUpdateAccessTimeWithKeys:(NSArray *)keys {
+    if (![self _dbCheck]) return NO;
+    int t = (int)time(NULL);
+     NSString *sql = [NSString stringWithFormat:@"update manifest set last_access_time = %d where key in (%@);", t, [self _dbJoinedKeys:keys]];
+    
+    sqlite3_stmt *stmt = NULL;
+    int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
+    if (result != SQLITE_OK) {
+        if (_errorLogsEnabled)  NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    
+    [self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
+    result = sqlite3_step(stmt);
+    sqlite3_finalize(stmt);
+    if (result != SQLITE_DONE) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite update error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    return YES;
+}
+
+- (BOOL)_dbDeleteItemWithKey:(NSString *)key {
+    NSString *sql = @"delete from manifest where key = ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return NO;
+    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
+    
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_DONE) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d db delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    return YES;
+}
+
+- (BOOL)_dbDeleteItemWithKeys:(NSArray *)keys {
+    if (![self _dbCheck]) return NO;
+    NSString *sql =  [NSString stringWithFormat:@"delete from manifest where key in (%@);", [self _dbJoinedKeys:keys]];
+    sqlite3_stmt *stmt = NULL;
+    int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
+    if (result != SQLITE_OK) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    
+    [self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
+    result = sqlite3_step(stmt);
+    sqlite3_finalize(stmt);
+    if (result == SQLITE_ERROR) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    return YES;
+}
+
+- (BOOL)_dbDeleteItemsWithSizeLargerThan:(int)size {
+    NSString *sql = @"delete from manifest where size > ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return NO;
+    sqlite3_bind_int(stmt, 1, size);
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_DONE) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    return YES;
+}
+
+- (BOOL)_dbDeleteItemsWithTimeEarlierThan:(int)time {
+    NSString *sql = @"delete from manifest where last_access_time < ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return NO;
+    sqlite3_bind_int(stmt, 1, time);
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_DONE) {
+        if (_errorLogsEnabled)  NSLog(@"%s line:%d sqlite delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return NO;
+    }
+    return YES;
+}
+
+- (YYKVStorageItem *)_dbGetItemFromStmt:(sqlite3_stmt *)stmt excludeInlineData:(BOOL)excludeInlineData {
+    int i = 0;
+    char *key = (char *)sqlite3_column_text(stmt, i++);
+    char *filename = (char *)sqlite3_column_text(stmt, i++);
+    int size = sqlite3_column_int(stmt, i++);
+    const void *inline_data = excludeInlineData ? NULL : sqlite3_column_blob(stmt, i);
+    int inline_data_bytes = excludeInlineData ? 0 : sqlite3_column_bytes(stmt, i++);
+    int modification_time = sqlite3_column_int(stmt, i++);
+    int last_access_time = sqlite3_column_int(stmt, i++);
+    const void *extended_data = sqlite3_column_blob(stmt, i);
+    int extended_data_bytes = sqlite3_column_bytes(stmt, i++);
+    
+    YYKVStorageItem *item = [YYKVStorageItem new];
+    if (key) item.key = [NSString stringWithUTF8String:key];
+    if (filename && *filename != 0) item.filename = [NSString stringWithUTF8String:filename];
+    item.size = size;
+    if (inline_data_bytes > 0 && inline_data) item.value = [NSData dataWithBytes:inline_data length:inline_data_bytes];
+    item.modTime = modification_time;
+    item.accessTime = last_access_time;
+    if (extended_data_bytes > 0 && extended_data) item.extendedData = [NSData dataWithBytes:extended_data length:extended_data_bytes];
+    return item;
+}
+
+- (YYKVStorageItem *)_dbGetItemWithKey:(NSString *)key excludeInlineData:(BOOL)excludeInlineData {
+    NSString *sql = excludeInlineData ? @"select key, filename, size, modification_time, last_access_time, extended_data from manifest where key = ?1;" : @"select key, filename, size, inline_data, modification_time, last_access_time, extended_data from manifest where key = ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return nil;
+    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
+    
+    YYKVStorageItem *item = nil;
+    int result = sqlite3_step(stmt);
+    if (result == SQLITE_ROW) {
+        item = [self _dbGetItemFromStmt:stmt excludeInlineData:excludeInlineData];
+    } else {
+        if (result != SQLITE_DONE) {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        }
+    }
+    return item;
+}
+
+- (NSMutableArray *)_dbGetItemWithKeys:(NSArray *)keys excludeInlineData:(BOOL)excludeInlineData {
+    if (![self _dbCheck]) return nil;
+    NSString *sql;
+    if (excludeInlineData) {
+        sql = [NSString stringWithFormat:@"select key, filename, size, modification_time, last_access_time, extended_data from manifest where key in (%@);", [self _dbJoinedKeys:keys]];
+    } else {
+        sql = [NSString stringWithFormat:@"select key, filename, size, inline_data, modification_time, last_access_time, extended_data from manifest where key in (%@)", [self _dbJoinedKeys:keys]];
+    }
+    
+    sqlite3_stmt *stmt = NULL;
+    int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
+    if (result != SQLITE_OK) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return nil;
+    }
+    
+    [self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
+    NSMutableArray *items = [NSMutableArray new];
+    do {
+        result = sqlite3_step(stmt);
+        if (result == SQLITE_ROW) {
+            YYKVStorageItem *item = [self _dbGetItemFromStmt:stmt excludeInlineData:excludeInlineData];
+            if (item) [items addObject:item];
+        } else if (result == SQLITE_DONE) {
+            break;
+        } else {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+            items = nil;
+            break;
+        }
+    } while (1);
+    sqlite3_finalize(stmt);
+    return items;
+}
+
+- (NSData *)_dbGetValueWithKey:(NSString *)key {
+    NSString *sql = @"select inline_data from manifest where key = ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return nil;
+    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
+    
+    int result = sqlite3_step(stmt);
+    if (result == SQLITE_ROW) {
+        const void *inline_data = sqlite3_column_blob(stmt, 0);
+        int inline_data_bytes = sqlite3_column_bytes(stmt, 0);
+        if (!inline_data || inline_data_bytes <= 0) return nil;
+        return [NSData dataWithBytes:inline_data length:inline_data_bytes];
+    } else {
+        if (result != SQLITE_DONE) {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        }
+        return nil;
+    }
+}
+
+- (NSString *)_dbGetFilenameWithKey:(NSString *)key {
+    NSString *sql = @"select filename from manifest where key = ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return nil;
+    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
+    int result = sqlite3_step(stmt);
+    if (result == SQLITE_ROW) {
+        char *filename = (char *)sqlite3_column_text(stmt, 0);
+        if (filename && *filename != 0) {
+            return [NSString stringWithUTF8String:filename];
+        }
+    } else {
+        if (result != SQLITE_DONE) {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        }
+    }
+    return nil;
+}
+
+- (NSMutableArray *)_dbGetFilenameWithKeys:(NSArray *)keys {
+    if (![self _dbCheck]) return nil;
+    NSString *sql = [NSString stringWithFormat:@"select filename from manifest where key in (%@);", [self _dbJoinedKeys:keys]];
+    sqlite3_stmt *stmt = NULL;
+    int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
+    if (result != SQLITE_OK) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return nil;
+    }
+    
+    [self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
+    NSMutableArray *filenames = [NSMutableArray new];
+    do {
+        result = sqlite3_step(stmt);
+        if (result == SQLITE_ROW) {
+            char *filename = (char *)sqlite3_column_text(stmt, 0);
+            if (filename && *filename != 0) {
+                NSString *name = [NSString stringWithUTF8String:filename];
+                if (name) [filenames addObject:name];
+            }
+        } else if (result == SQLITE_DONE) {
+            break;
+        } else {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+            filenames = nil;
+            break;
+        }
+    } while (1);
+    sqlite3_finalize(stmt);
+    return filenames;
+}
+
+- (NSMutableArray *)_dbGetFilenamesWithSizeLargerThan:(int)size {
+    NSString *sql = @"select filename from manifest where size > ?1 and filename is not null;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return nil;
+    sqlite3_bind_int(stmt, 1, size);
+    
+    NSMutableArray *filenames = [NSMutableArray new];
+    do {
+        int result = sqlite3_step(stmt);
+        if (result == SQLITE_ROW) {
+            char *filename = (char *)sqlite3_column_text(stmt, 0);
+            if (filename && *filename != 0) {
+                NSString *name = [NSString stringWithUTF8String:filename];
+                if (name) [filenames addObject:name];
+            }
+        } else if (result == SQLITE_DONE) {
+            break;
+        } else {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+            filenames = nil;
+            break;
+        }
+    } while (1);
+    return filenames;
+}
+
+- (NSMutableArray *)_dbGetFilenamesWithTimeEarlierThan:(int)time {
+    NSString *sql = @"select filename from manifest where last_access_time < ?1 and filename is not null;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return nil;
+    sqlite3_bind_int(stmt, 1, time);
+    
+    NSMutableArray *filenames = [NSMutableArray new];
+    do {
+        int result = sqlite3_step(stmt);
+        if (result == SQLITE_ROW) {
+            char *filename = (char *)sqlite3_column_text(stmt, 0);
+            if (filename && *filename != 0) {
+                NSString *name = [NSString stringWithUTF8String:filename];
+                if (name) [filenames addObject:name];
+            }
+        } else if (result == SQLITE_DONE) {
+            break;
+        } else {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+            filenames = nil;
+            break;
+        }
+    } while (1);
+    return filenames;
+}
+
+- (NSMutableArray *)_dbGetItemSizeInfoOrderByTimeAscWithLimit:(int)count {
+    NSString *sql = @"select key, filename, size from manifest order by last_access_time asc limit ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return nil;
+    sqlite3_bind_int(stmt, 1, count);
+    
+    NSMutableArray *items = [NSMutableArray new];
+    do {
+        int result = sqlite3_step(stmt);
+        if (result == SQLITE_ROW) {
+            char *key = (char *)sqlite3_column_text(stmt, 0);
+            char *filename = (char *)sqlite3_column_text(stmt, 1);
+            int size = sqlite3_column_int(stmt, 2);
+            NSString *keyStr = key ? [NSString stringWithUTF8String:key] : nil;
+            if (keyStr) {
+                YYKVStorageItem *item = [YYKVStorageItem new];
+                item.key = key ? [NSString stringWithUTF8String:key] : nil;
+                item.filename = filename ? [NSString stringWithUTF8String:filename] : nil;
+                item.size = size;
+                [items addObject:item];
+            }
+        } else if (result == SQLITE_DONE) {
+            break;
+        } else {
+            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+            items = nil;
+            break;
+        }
+    } while (1);
+    return items;
+}
+
+- (int)_dbGetItemCountWithKey:(NSString *)key {
+    NSString *sql = @"select count(key) from manifest where key = ?1;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return -1;
+    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_ROW) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return -1;
+    }
+    return sqlite3_column_int(stmt, 0);
+}
+
+- (int)_dbGetTotalItemSize {
+    NSString *sql = @"select sum(size) from manifest;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return -1;
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_ROW) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return -1;
+    }
+    return sqlite3_column_int(stmt, 0);
+}
+
+- (int)_dbGetTotalItemCount {
+    NSString *sql = @"select count(*) from manifest;";
+    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
+    if (!stmt) return -1;
+    int result = sqlite3_step(stmt);
+    if (result != SQLITE_ROW) {
+        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
+        return -1;
+    }
+    return sqlite3_column_int(stmt, 0);
+}
+
+
+#pragma mark - file
+
+- (BOOL)_fileWriteWithName:(NSString *)filename data:(NSData *)data {
+    NSString *path = [_dataPath stringByAppendingPathComponent:filename];
+    return [data writeToFile:path atomically:NO];
+}
+
+- (NSData *)_fileReadWithName:(NSString *)filename {
+    NSString *path = [_dataPath stringByAppendingPathComponent:filename];
+    NSData *data = [NSData dataWithContentsOfFile:path];
+    return data;
+}
+
+- (BOOL)_fileDeleteWithName:(NSString *)filename {
+    NSString *path = [_dataPath stringByAppendingPathComponent:filename];
+    return [[NSFileManager defaultManager] removeItemAtPath:path error:NULL];
+}
+
+- (BOOL)_fileMoveAllToTrash {
+    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
+    CFStringRef uuid = CFUUIDCreateString(NULL, uuidRef);
+    CFRelease(uuidRef);
+    NSString *tmpPath = [_trashPath stringByAppendingPathComponent:(__bridge NSString *)(uuid)];
+    BOOL suc = [[NSFileManager defaultManager] moveItemAtPath:_dataPath toPath:tmpPath error:nil];
+    if (suc) {
+        suc = [[NSFileManager defaultManager] createDirectoryAtPath:_dataPath withIntermediateDirectories:YES attributes:nil error:NULL];
+    }
+    CFRelease(uuid);
+    return suc;
+}
+
+- (void)_fileEmptyTrashInBackground {
+    NSString *trashPath = _trashPath;
+    dispatch_queue_t queue = _trashQueue;
+    dispatch_async(queue, ^{
+        NSFileManager *manager = [NSFileManager new];
+        NSArray *directoryContents = [manager contentsOfDirectoryAtPath:trashPath error:NULL];
+        for (NSString *path in directoryContents) {
+            NSString *fullPath = [trashPath stringByAppendingPathComponent:path];
+            [manager removeItemAtPath:fullPath error:NULL];
+        }
+    });
+}
+
+
+#pragma mark - private
+
+/**
+ Delete all files and empty in background.
+ Make sure the db is closed.
+ */
+- (void)_reset {
+    [[NSFileManager defaultManager] removeItemAtPath:[_path stringByAppendingPathComponent:kDBFileName] error:nil];
+    [[NSFileManager defaultManager] removeItemAtPath:[_path stringByAppendingPathComponent:kDBShmFileName] error:nil];
+    [[NSFileManager defaultManager] removeItemAtPath:[_path stringByAppendingPathComponent:kDBWalFileName] error:nil];
+    [self _fileMoveAllToTrash];
+    [self _fileEmptyTrashInBackground];
+}
+
+#pragma mark - public
+
+- (instancetype)init {
+    @throw [NSException exceptionWithName:@"YYKVStorage init error" reason:@"Please use the designated initializer and pass the 'path' and 'type'." userInfo:nil];
+    return [self initWithPath:@"" type:YYKVStorageTypeFile];
+}
+
+- (instancetype)initWithPath:(NSString *)path type:(YYKVStorageType)type {
+    if (path.length == 0 || path.length > kPathLengthMax) {
+        NSLog(@"YYKVStorage init error: invalid path: [%@].", path);
+        return nil;
+    }
+    if (type > YYKVStorageTypeMixed) {
+        NSLog(@"YYKVStorage init error: invalid type: %lu.", (unsigned long)type);
+        return nil;
+    }
+    
+    self = [super init];
+    _path = path.copy;
+    _type = type;
+    _dataPath = [path stringByAppendingPathComponent:kDataDirectoryName];
+    _trashPath = [path stringByAppendingPathComponent:kTrashDirectoryName];
+    _trashQueue = dispatch_queue_create("com.ibireme.cache.disk.trash", DISPATCH_QUEUE_SERIAL);
+    _dbPath = [path stringByAppendingPathComponent:kDBFileName];
+    _errorLogsEnabled = YES;
+    NSError *error = nil;
+    if (![[NSFileManager defaultManager] createDirectoryAtPath:path
+                                   withIntermediateDirectories:YES
+                                                    attributes:nil
+                                                         error:&error] ||
+        ![[NSFileManager defaultManager] createDirectoryAtPath:[path stringByAppendingPathComponent:kDataDirectoryName]
+                                   withIntermediateDirectories:YES
+                                                    attributes:nil
+                                                         error:&error] ||
+        ![[NSFileManager defaultManager] createDirectoryAtPath:[path stringByAppendingPathComponent:kTrashDirectoryName]
+                                   withIntermediateDirectories:YES
+                                                    attributes:nil
+                                                         error:&error]) {
+        NSLog(@"YYKVStorage init error:%@", error);
+        return nil;
+    }
+    
+    if (![self _dbOpen] || ![self _dbInitialize]) {
+        // db file may broken...
+        [self _dbClose];
+        [self _reset]; // rebuild
+        if (![self _dbOpen] || ![self _dbInitialize]) {
+            [self _dbClose];
+            NSLog(@"YYKVStorage init error: fail to open sqlite db.");
+            return nil;
+        }
+    }
+    [self _fileEmptyTrashInBackground]; // empty the trash if failed at last time
+    return self;
+}
+
+- (void)dealloc {
+    UIBackgroundTaskIdentifier taskID = [[UIApplication sharedExtensionApplication] beginBackgroundTaskWithExpirationHandler:^{}];
+    [self _dbClose];
+    if (taskID != UIBackgroundTaskInvalid) {
+        [[UIApplication sharedExtensionApplication] endBackgroundTask:taskID];
+    }
+}
+
+- (BOOL)saveItem:(YYKVStorageItem *)item {
+    return [self saveItemWithKey:item.key value:item.value filename:item.filename extendedData:item.extendedData];
+}
+
+- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value {
+    return [self saveItemWithKey:key value:value filename:nil extendedData:nil];
+}
+
+- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value filename:(NSString *)filename extendedData:(NSData *)extendedData {
+    if (key.length == 0 || value.length == 0) return NO;
+    if (_type == YYKVStorageTypeFile && filename.length == 0) {
+        return NO;
+    }
+    
+    if (filename.length) {
+        if (![self _fileWriteWithName:filename data:value]) {
+            return NO;
+        }
+        if (![self _dbSaveWithKey:key value:value fileName:filename extendedData:extendedData]) {
+            [self _fileDeleteWithName:filename];
+            return NO;
+        }
+        return YES;
+    } else {
+        if (_type != YYKVStorageTypeSQLite) {
+            NSString *filename = [self _dbGetFilenameWithKey:key];
+            if (filename) {
+                [self _fileDeleteWithName:filename];
+            }
+        }
+        return [self _dbSaveWithKey:key value:value fileName:nil extendedData:extendedData];
+    }
+}
+
+- (BOOL)removeItemForKey:(NSString *)key {
+    if (key.length == 0) return NO;
+    switch (_type) {
+        case YYKVStorageTypeSQLite: {
+            return [self _dbDeleteItemWithKey:key];
+        } break;
+        case YYKVStorageTypeFile:
+        case YYKVStorageTypeMixed: {
+            NSString *filename = [self _dbGetFilenameWithKey:key];
+            if (filename) {
+                [self _fileDeleteWithName:filename];
+            }
+            return [self _dbDeleteItemWithKey:key];
+        } break;
+        default: return NO;
+    }
+}
+
+- (BOOL)removeItemForKeys:(NSArray *)keys {
+    if (keys.count == 0) return NO;
+    switch (_type) {
+        case YYKVStorageTypeSQLite: {
+            return [self _dbDeleteItemWithKeys:keys];
+        } break;
+        case YYKVStorageTypeFile:
+        case YYKVStorageTypeMixed: {
+            NSArray *filenames = [self _dbGetFilenameWithKeys:keys];
+            for (NSString *filename in filenames) {
+                [self _fileDeleteWithName:filename];
+            }
+            return [self _dbDeleteItemWithKeys:keys];
+        } break;
+        default: return NO;
+    }
+}
+
+- (BOOL)removeItemsLargerThanSize:(int)size {
+    if (size == INT_MAX) return YES;
+    if (size <= 0) return [self removeAllItems];
+    
+    switch (_type) {
+        case YYKVStorageTypeSQLite: {
+            if ([self _dbDeleteItemsWithSizeLargerThan:size]) {
+                [self _dbCheckpoint];
+                return YES;
+            }
+        } break;
+        case YYKVStorageTypeFile:
+        case YYKVStorageTypeMixed: {
+            NSArray *filenames = [self _dbGetFilenamesWithSizeLargerThan:size];
+            for (NSString *name in filenames) {
+                [self _fileDeleteWithName:name];
+            }
+            if ([self _dbDeleteItemsWithSizeLargerThan:size]) {
+                [self _dbCheckpoint];
+                return YES;
+            }
+        } break;
+    }
+    return NO;
+}
+
+- (BOOL)removeItemsEarlierThanTime:(int)time {
+    if (time <= 0) return YES;
+    if (time == INT_MAX) return [self removeAllItems];
+    
+    switch (_type) {
+        case YYKVStorageTypeSQLite: {
+            if ([self _dbDeleteItemsWithTimeEarlierThan:time]) {
+                [self _dbCheckpoint];
+                return YES;
+            }
+        } break;
+        case YYKVStorageTypeFile:
+        case YYKVStorageTypeMixed: {
+            NSArray *filenames = [self _dbGetFilenamesWithTimeEarlierThan:time];
+            for (NSString *name in filenames) {
+                [self _fileDeleteWithName:name];
+            }
+            if ([self _dbDeleteItemsWithTimeEarlierThan:time]) {
+                [self _dbCheckpoint];
+                return YES;
+            }
+        } break;
+    }
+    return NO;
+}
+
+- (BOOL)removeItemsToFitSize:(int)maxSize {
+    if (maxSize == INT_MAX) return YES;
+    if (maxSize <= 0) return [self removeAllItems];
+    
+    int total = [self _dbGetTotalItemSize];
+    if (total < 0) return NO;
+    if (total <= maxSize) return YES;
+    
+    NSArray *items = nil;
+    BOOL suc = NO;
+    do {
+        int perCount = 16;
+        items = [self _dbGetItemSizeInfoOrderByTimeAscWithLimit:perCount];
+        for (YYKVStorageItem *item in items) {
+            if (total > maxSize) {
+                if (item.filename) {
+                    [self _fileDeleteWithName:item.filename];
+                }
+                suc = [self _dbDeleteItemWithKey:item.key];
+                total -= item.size;
+            } else {
+                break;
+            }
+            if (!suc) break;
+        }
+    } while (total > maxSize && items.count > 0 && suc);
+    if (suc) [self _dbCheckpoint];
+    return suc;
+}
+
+- (BOOL)removeItemsToFitCount:(int)maxCount {
+    if (maxCount == INT_MAX) return YES;
+    if (maxCount <= 0) return [self removeAllItems];
+    
+    int total = [self _dbGetTotalItemCount];
+    if (total < 0) return NO;
+    if (total <= maxCount) return YES;
+    
+    NSArray *items = nil;
+    BOOL suc = NO;
+    do {
+        int perCount = 16;
+        items = [self _dbGetItemSizeInfoOrderByTimeAscWithLimit:perCount];
+        for (YYKVStorageItem *item in items) {
+            if (total > maxCount) {
+                if (item.filename) {
+                    [self _fileDeleteWithName:item.filename];
+                }
+                suc = [self _dbDeleteItemWithKey:item.key];
+                total--;
+            } else {
+                break;
+            }
+            if (!suc) break;
+        }
+    } while (total > maxCount && items.count > 0 && suc);
+    if (suc) [self _dbCheckpoint];
+    return suc;
+}
+
+- (BOOL)removeAllItems {
+    if (![self _dbClose]) return NO;
+    [self _reset];
+    if (![self _dbOpen]) return NO;
+    if (![self _dbInitialize]) return NO;
+    return YES;
+}
+
+- (void)removeAllItemsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress
+                               endBlock:(void(^)(BOOL error))end {
+    
+    int total = [self _dbGetTotalItemCount];
+    if (total <= 0) {
+        if (end) end(total < 0);
+    } else {
+        int left = total;
+        int perCount = 32;
+        NSArray *items = nil;
+        BOOL suc = NO;
+        do {
+            items = [self _dbGetItemSizeInfoOrderByTimeAscWithLimit:perCount];
+            for (YYKVStorageItem *item in items) {
+                if (left > 0) {
+                    if (item.filename) {
+                        [self _fileDeleteWithName:item.filename];
+                    }
+                    suc = [self _dbDeleteItemWithKey:item.key];
+                    left--;
+                } else {
+                    break;
+                }
+                if (!suc) break;
+            }
+            if (progress) progress(total - left, total);
+        } while (left > 0 && items.count > 0 && suc);
+        if (suc) [self _dbCheckpoint];
+        if (end) end(!suc);
+    }
+}
+
+- (YYKVStorageItem *)getItemForKey:(NSString *)key {
+    if (key.length == 0) return nil;
+    YYKVStorageItem *item = [self _dbGetItemWithKey:key excludeInlineData:NO];
+    if (item) {
+        [self _dbUpdateAccessTimeWithKey:key];
+        if (item.filename) {
+            item.value = [self _fileReadWithName:item.filename];
+            if (!item.value) {
+                [self _dbDeleteItemWithKey:key];
+                item = nil;
+            }
+        }
+    }
+    return item;
+}
+
+- (YYKVStorageItem *)getItemInfoForKey:(NSString *)key {
+    if (key.length == 0) return nil;
+    YYKVStorageItem *item = [self _dbGetItemWithKey:key excludeInlineData:YES];
+    return item;
+}
+
+- (NSData *)getItemValueForKey:(NSString *)key {
+    if (key.length == 0) return nil;
+    NSData *value = nil;
+    switch (_type) {
+        case YYKVStorageTypeFile: {
+            NSString *filename = [self _dbGetFilenameWithKey:key];
+            if (filename) {
+                value = [self _fileReadWithName:filename];
+                if (!value) {
+                    [self _dbDeleteItemWithKey:key];
+                    value = nil;
+                }
+            }
+        } break;
+        case YYKVStorageTypeSQLite: {
+            value = [self _dbGetValueWithKey:key];
+        } break;
+        case YYKVStorageTypeMixed: {
+            NSString *filename = [self _dbGetFilenameWithKey:key];
+            if (filename) {
+                value = [self _fileReadWithName:filename];
+                if (!value) {
+                    [self _dbDeleteItemWithKey:key];
+                    value = nil;
+                }
+            } else {
+                value = [self _dbGetValueWithKey:key];
+            }
+        } break;
+    }
+    if (value) {
+        [self _dbUpdateAccessTimeWithKey:key];
+    }
+    return value;
+}
+
+- (NSArray *)getItemForKeys:(NSArray *)keys {
+    if (keys.count == 0) return nil;
+    NSMutableArray *items = [self _dbGetItemWithKeys:keys excludeInlineData:NO];
+    if (_type != YYKVStorageTypeSQLite) {
+        for (NSInteger i = 0, max = items.count; i < max; i++) {
+            YYKVStorageItem *item = items[i];
+            if (item.filename) {
+                item.value = [self _fileReadWithName:item.filename];
+                if (!item.value) {
+                    if (item.key) [self _dbDeleteItemWithKey:item.key];
+                    [items removeObjectAtIndex:i];
+                    i--;
+                    max--;
+                }
+            }
+        }
+    }
+    if (items.count > 0) {
+        [self _dbUpdateAccessTimeWithKeys:keys];
+    }
+    return items.count ? items : nil;
+}
+
+- (NSArray *)getItemInfoForKeys:(NSArray *)keys {
+    if (keys.count == 0) return nil;
+    return [self _dbGetItemWithKeys:keys excludeInlineData:YES];
+}
+
+- (NSDictionary *)getItemValueForKeys:(NSArray *)keys {
+    NSMutableArray *items = (NSMutableArray *)[self getItemForKeys:keys];
+    NSMutableDictionary *kv = [NSMutableDictionary new];
+    for (YYKVStorageItem *item in items) {
+        if (item.key && item.value) {
+            [kv setObject:item.value forKey:item.key];
+        }
+    }
+    return kv.count ? kv : nil;
+}
+
+- (BOOL)itemExistsForKey:(NSString *)key {
+    if (key.length == 0) return NO;
+    return [self _dbGetItemCountWithKey:key] > 0;
+}
+
+- (int)getItemsCount {
+    return [self _dbGetTotalItemCount];
+}
+
+- (int)getItemsSize {
+    return [self _dbGetTotalItemSize];
+}
+
+@end

+ 213 - 0
YYKit/Cache/YYMemoryCache.h

@@ -0,0 +1,213 @@
+//
+//  YYMemoryCache.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/7.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ YYMemoryCache is a fast in-memory cache that stores key-value pairs.
+ In contrast to NSDictionary, keys are retained and not copied.
+ The API and performance is similar to `NSCache`, all methods are thread-safe.
+ 
+ YYMemoryCache objects differ from NSCache in a few ways:
+ 
+ * It uses LRU (least-recently-used) to remove objects; NSCache's eviction method
+   is non-deterministic.
+ * It can be controlled by cost, count and age; NSCache's limits are imprecise.
+ * It can be configured to automatically evict objects when receive memory 
+   warning or app enter background.
+ 
+ The time of `Access Methods` in YYMemoryCache is typically in constant time (O(1)).
+ */
+@interface YYMemoryCache : NSObject
+
+#pragma mark - Attribute
+///=============================================================================
+/// @name Attribute
+///=============================================================================
+
+/** The name of the cache. Default is nil. */
+@property (nullable, copy) NSString *name;
+
+/** The number of objects in the cache (read-only) */
+@property (readonly) NSUInteger totalCount;
+
+/** The total cost of objects in the cache (read-only). */
+@property (readonly) NSUInteger totalCost;
+
+
+#pragma mark - Limit
+///=============================================================================
+/// @name Limit
+///=============================================================================
+
+/**
+ The maximum number of objects the cache should hold.
+ 
+ @discussion The default value is NSUIntegerMax, which means no limit.
+ This is not a strict limit—if the cache goes over the limit, some objects in the
+ cache could be evicted later in backgound thread.
+ */
+@property NSUInteger countLimit;
+
+/**
+ The maximum total cost that the cache can hold before it starts evicting objects.
+ 
+ @discussion The default value is NSUIntegerMax, which means no limit.
+ This is not a strict limit—if the cache goes over the limit, some objects in the
+ cache could be evicted later in backgound thread.
+ */
+@property NSUInteger costLimit;
+
+/**
+ The maximum expiry time of objects in cache.
+ 
+ @discussion The default value is DBL_MAX, which means no limit.
+ This is not a strict limit—if an object goes over the limit, the object could 
+ be evicted later in backgound thread.
+ */
+@property NSTimeInterval ageLimit;
+
+/**
+ The auto trim check time interval in seconds. Default is 5.0.
+ 
+ @discussion The cache holds an internal timer to check whether the cache reaches 
+ its limits, and if the limit is reached, it begins to evict objects.
+ */
+@property NSTimeInterval autoTrimInterval;
+
+/**
+ If `YES`, the cache will remove all objects when the app receives a memory warning.
+ The default value is `YES`.
+ */
+@property BOOL shouldRemoveAllObjectsOnMemoryWarning;
+
+/**
+ If `YES`, The cache will remove all objects when the app enter background.
+ The default value is `YES`.
+ */
+@property BOOL shouldRemoveAllObjectsWhenEnteringBackground;
+
+/**
+ A block to be executed when the app receives a memory warning.
+ The default value is nil.
+ */
+@property (nullable, copy) void(^didReceiveMemoryWarningBlock)(YYMemoryCache *cache);
+
+/**
+ A block to be executed when the app enter background.
+ The default value is nil.
+ */
+@property (nullable, copy) void(^didEnterBackgroundBlock)(YYMemoryCache *cache);
+
+/**
+ If `YES`, the key-value pair will be released on main thread, otherwise on
+ background thread. Default is NO.
+ 
+ @discussion You may set this value to `YES` if the key-value object contains
+ the instance which should be released in main thread (such as UIView/CALayer).
+ */
+@property BOOL releaseOnMainThread;
+
+/**
+ If `YES`, the key-value pair will be released asynchronously to avoid blocking 
+ the access methods, otherwise it will be released in the access method  
+ (such as removeObjectForKey:). Default is YES.
+ */
+@property BOOL releaseAsynchronously;
+
+
+#pragma mark - Access Methods
+///=============================================================================
+/// @name Access Methods
+///=============================================================================
+
+/**
+ Returns a Boolean value that indicates whether a given key is in cache.
+ 
+ @param key An object identifying the value. If nil, just return `NO`.
+ @return Whether the key is in cache.
+ */
+- (BOOL)containsObjectForKey:(id)key;
+
+/**
+ Returns the value associated with a given key.
+ 
+ @param key An object identifying the value. If nil, just return nil.
+ @return The value associated with key, or nil if no value is associated with key.
+ */
+- (nullable id)objectForKey:(id)key;
+
+/**
+ Sets the value of the specified key in the cache (0 cost).
+ 
+ @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
+ @param key    The key with which to associate the value. If nil, this method has no effect.
+ @discussion Unlike an NSMutableDictionary object, a cache does not copy the key 
+ objects that are put into it.
+ */
+- (void)setObject:(nullable id)object forKey:(id)key;
+
+/**
+ Sets the value of the specified key in the cache, and associates the key-value 
+ pair with the specified cost.
+ 
+ @param object The object to store in the cache. If nil, it calls `removeObjectForKey`.
+ @param key    The key with which to associate the value. If nil, this method has no effect.
+ @param cost   The cost with which to associate the key-value pair.
+ @discussion Unlike an NSMutableDictionary object, a cache does not copy the key
+ objects that are put into it.
+ */
+- (void)setObject:(nullable id)object forKey:(id)key withCost:(NSUInteger)cost;
+
+/**
+ Removes the value of the specified key in the cache.
+ 
+ @param key The key identifying the value to be removed. If nil, this method has no effect.
+ */
+- (void)removeObjectForKey:(id)key;
+
+/**
+ Empties the cache immediately.
+ */
+- (void)removeAllObjects;
+
+
+#pragma mark - Trim
+///=============================================================================
+/// @name Trim
+///=============================================================================
+
+/**
+ Removes objects from the cache with LRU, until the `totalCount` is below or equal to
+ the specified value.
+ @param count  The total count allowed to remain after the cache has been trimmed.
+ */
+- (void)trimToCount:(NSUInteger)count;
+
+/**
+ Removes objects from the cache with LRU, until the `totalCost` is or equal to
+ the specified value.
+ @param cost The total cost allowed to remain after the cache has been trimmed.
+ */
+- (void)trimToCost:(NSUInteger)cost;
+
+/**
+ Removes objects from the cache with LRU, until all expiry objects removed by the
+ specified value.
+ @param age  The maximum age (in seconds) of objects.
+ */
+- (void)trimToAge:(NSTimeInterval)age;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 514 - 0
YYKit/Cache/YYMemoryCache.m

@@ -0,0 +1,514 @@
+//
+//  YYMemoryCache.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/7.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYMemoryCache.h"
+#import <UIKit/UIKit.h>
+#import <CoreFoundation/CoreFoundation.h>
+#import <QuartzCore/QuartzCore.h>
+#import <pthread.h>
+
+#if __has_include("YYDispatchQueuePool.h")
+#import "YYDispatchQueuePool.h"
+#endif
+
+#ifdef YYDispatchQueuePool_h
+static inline dispatch_queue_t YYMemoryCacheGetReleaseQueue() {
+    return YYDispatchQueueGetForQOS(NSQualityOfServiceUtility);
+}
+#else
+static inline dispatch_queue_t YYMemoryCacheGetReleaseQueue() {
+    return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
+}
+#endif
+
+/**
+ A node in linked map.
+ Typically, you should not use this class directly.
+ */
+@interface _YYLinkedMapNode : NSObject {
+    @package
+    __unsafe_unretained _YYLinkedMapNode *_prev; // retained by dic
+    __unsafe_unretained _YYLinkedMapNode *_next; // retained by dic
+    id _key;
+    id _value;
+    NSUInteger _cost;
+    NSTimeInterval _time;
+}
+@end
+
+@implementation _YYLinkedMapNode
+@end
+
+
+/**
+ A linked map used by YYMemoryCache.
+ It's not thread-safe and does not validate the parameters.
+ 
+ Typically, you should not use this class directly.
+ */
+@interface _YYLinkedMap : NSObject {
+    @package
+    CFMutableDictionaryRef _dic; // do not set object directly
+    NSUInteger _totalCost;
+    NSUInteger _totalCount;
+    _YYLinkedMapNode *_head; // MRU, do not change it directly
+    _YYLinkedMapNode *_tail; // LRU, do not change it directly
+    BOOL _releaseOnMainThread;
+    BOOL _releaseAsynchronously;
+}
+
+/// Insert a node at head and update the total cost.
+/// Node and node.key should not be nil.
+- (void)insertNodeAtHead:(_YYLinkedMapNode *)node;
+
+/// Bring a inner node to header.
+/// Node should already inside the dic.
+- (void)bringNodeToHead:(_YYLinkedMapNode *)node;
+
+/// Remove a inner node and update the total cost.
+/// Node should already inside the dic.
+- (void)removeNode:(_YYLinkedMapNode *)node;
+
+/// Remove tail node if exist.
+- (_YYLinkedMapNode *)removeTailNode;
+
+/// Remove all node in background queue.
+- (void)removeAll;
+
+@end
+
+@implementation _YYLinkedMap
+
+- (instancetype)init {
+    self = [super init];
+    _dic = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
+    _releaseOnMainThread = NO;
+    _releaseAsynchronously = YES;
+    return self;
+}
+
+- (void)dealloc {
+    CFRelease(_dic);
+}
+
+- (void)insertNodeAtHead:(_YYLinkedMapNode *)node {
+    CFDictionarySetValue(_dic, (__bridge const void *)(node->_key), (__bridge const void *)(node));
+    _totalCost += node->_cost;
+    _totalCount++;
+    if (_head) {
+        node->_next = _head;
+        _head->_prev = node;
+        _head = node;
+    } else {
+        _head = _tail = node;
+    }
+}
+
+- (void)bringNodeToHead:(_YYLinkedMapNode *)node {
+    if (_head == node) return;
+    
+    if (_tail == node) {
+        _tail = node->_prev;
+        _tail->_next = nil;
+    } else {
+        node->_next->_prev = node->_prev;
+        node->_prev->_next = node->_next;
+    }
+    node->_next = _head;
+    node->_prev = nil;
+    _head->_prev = node;
+    _head = node;
+}
+
+- (void)removeNode:(_YYLinkedMapNode *)node {
+    CFDictionaryRemoveValue(_dic, (__bridge const void *)(node->_key));
+    _totalCost -= node->_cost;
+    _totalCount--;
+    if (node->_next) node->_next->_prev = node->_prev;
+    if (node->_prev) node->_prev->_next = node->_next;
+    if (_head == node) _head = node->_next;
+    if (_tail == node) _tail = node->_prev;
+}
+
+- (_YYLinkedMapNode *)removeTailNode {
+    if (!_tail) return nil;
+    _YYLinkedMapNode *tail = _tail;
+    CFDictionaryRemoveValue(_dic, (__bridge const void *)(_tail->_key));
+    _totalCost -= _tail->_cost;
+    _totalCount--;
+    if (_head == _tail) {
+        _head = _tail = nil;
+    } else {
+        _tail = _tail->_prev;
+        _tail->_next = nil;
+    }
+    return tail;
+}
+
+- (void)removeAll {
+    _totalCost = 0;
+    _totalCount = 0;
+    _head = nil;
+    _tail = nil;
+    if (CFDictionaryGetCount(_dic) > 0) {
+        CFMutableDictionaryRef holder = _dic;
+        _dic = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
+        
+        if (_releaseAsynchronously) {
+            dispatch_queue_t queue = _releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
+            dispatch_async(queue, ^{
+                CFRelease(holder); // hold and release in specified queue
+            });
+        } else if (_releaseOnMainThread && !pthread_main_np()) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                CFRelease(holder); // hold and release in specified queue
+            });
+        } else {
+            CFRelease(holder);
+        }
+    }
+}
+
+@end
+
+
+
+@implementation YYMemoryCache {
+    pthread_mutex_t _lock;
+    _YYLinkedMap *_lru;
+    dispatch_queue_t _queue;
+}
+
+- (void)_trimRecursively {
+    __weak typeof(self) _self = self;
+    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_autoTrimInterval * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
+        __strong typeof(_self) self = _self;
+        if (!self) return;
+        [self _trimInBackground];
+        [self _trimRecursively];
+    });
+}
+
+- (void)_trimInBackground {
+    dispatch_async(_queue, ^{
+        [self _trimToCost:self->_costLimit];
+        [self _trimToCount:self->_countLimit];
+        [self _trimToAge:self->_ageLimit];
+    });
+}
+
+- (void)_trimToCost:(NSUInteger)costLimit {
+    BOOL finish = NO;
+    pthread_mutex_lock(&_lock);
+    if (costLimit == 0) {
+        [_lru removeAll];
+        finish = YES;
+    } else if (_lru->_totalCost <= costLimit) {
+        finish = YES;
+    }
+    pthread_mutex_unlock(&_lock);
+    if (finish) return;
+    
+    NSMutableArray *holder = [NSMutableArray new];
+    while (!finish) {
+        if (pthread_mutex_trylock(&_lock) == 0) {
+            if (_lru->_totalCost > costLimit) {
+                _YYLinkedMapNode *node = [_lru removeTailNode];
+                if (node) [holder addObject:node];
+            } else {
+                finish = YES;
+            }
+            pthread_mutex_unlock(&_lock);
+        } else {
+            usleep(10 * 1000); //10 ms
+        }
+    }
+    if (holder.count) {
+        dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
+        dispatch_async(queue, ^{
+            [holder count]; // release in queue
+        });
+    }
+}
+
+- (void)_trimToCount:(NSUInteger)countLimit {
+    BOOL finish = NO;
+    pthread_mutex_lock(&_lock);
+    if (countLimit == 0) {
+        [_lru removeAll];
+        finish = YES;
+    } else if (_lru->_totalCount <= countLimit) {
+        finish = YES;
+    }
+    pthread_mutex_unlock(&_lock);
+    if (finish) return;
+    
+    NSMutableArray *holder = [NSMutableArray new];
+    while (!finish) {
+        if (pthread_mutex_trylock(&_lock) == 0) {
+            if (_lru->_totalCount > countLimit) {
+                _YYLinkedMapNode *node = [_lru removeTailNode];
+                if (node) [holder addObject:node];
+            } else {
+                finish = YES;
+            }
+            pthread_mutex_unlock(&_lock);
+        } else {
+            usleep(10 * 1000); //10 ms
+        }
+    }
+    if (holder.count) {
+        dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
+        dispatch_async(queue, ^{
+            [holder count]; // release in queue
+        });
+    }
+}
+
+- (void)_trimToAge:(NSTimeInterval)ageLimit {
+    BOOL finish = NO;
+    NSTimeInterval now = CACurrentMediaTime();
+    pthread_mutex_lock(&_lock);
+    if (ageLimit <= 0) {
+        [_lru removeAll];
+        finish = YES;
+    } else if (!_lru->_tail || (now - _lru->_tail->_time) <= ageLimit) {
+        finish = YES;
+    }
+    pthread_mutex_unlock(&_lock);
+    if (finish) return;
+    
+    NSMutableArray *holder = [NSMutableArray new];
+    while (!finish) {
+        if (pthread_mutex_trylock(&_lock) == 0) {
+            if (_lru->_tail && (now - _lru->_tail->_time) > ageLimit) {
+                _YYLinkedMapNode *node = [_lru removeTailNode];
+                if (node) [holder addObject:node];
+            } else {
+                finish = YES;
+            }
+            pthread_mutex_unlock(&_lock);
+        } else {
+            usleep(10 * 1000); //10 ms
+        }
+    }
+    if (holder.count) {
+        dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
+        dispatch_async(queue, ^{
+            [holder count]; // release in queue
+        });
+    }
+}
+
+- (void)_appDidReceiveMemoryWarningNotification {
+    if (self.didReceiveMemoryWarningBlock) {
+        self.didReceiveMemoryWarningBlock(self);
+    }
+    if (self.shouldRemoveAllObjectsOnMemoryWarning) {
+        [self removeAllObjects];
+    }
+}
+
+- (void)_appDidEnterBackgroundNotification {
+    if (self.didEnterBackgroundBlock) {
+        self.didEnterBackgroundBlock(self);
+    }
+    if (self.shouldRemoveAllObjectsWhenEnteringBackground) {
+        [self removeAllObjects];
+    }
+}
+
+#pragma mark - public
+
+- (instancetype)init {
+    self = super.init;
+    pthread_mutex_init(&_lock, NULL);
+    _lru = [_YYLinkedMap new];
+    _queue = dispatch_queue_create("com.ibireme.cache.memory", DISPATCH_QUEUE_SERIAL);
+    
+    _countLimit = NSUIntegerMax;
+    _costLimit = NSUIntegerMax;
+    _ageLimit = DBL_MAX;
+    _autoTrimInterval = 5.0;
+    _shouldRemoveAllObjectsOnMemoryWarning = YES;
+    _shouldRemoveAllObjectsWhenEnteringBackground = YES;
+    
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appDidReceiveMemoryWarningNotification) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appDidEnterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
+    
+    [self _trimRecursively];
+    return self;
+}
+
+- (void)dealloc {
+    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
+    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
+    [_lru removeAll];
+    pthread_mutex_destroy(&_lock);
+}
+
+- (NSUInteger)totalCount {
+    pthread_mutex_lock(&_lock);
+    NSUInteger count = _lru->_totalCount;
+    pthread_mutex_unlock(&_lock);
+    return count;
+}
+
+- (NSUInteger)totalCost {
+    pthread_mutex_lock(&_lock);
+    NSUInteger totalCost = _lru->_totalCost;
+    pthread_mutex_unlock(&_lock);
+    return totalCost;
+}
+
+- (BOOL)releaseOnMainThread {
+    pthread_mutex_lock(&_lock);
+    BOOL releaseOnMainThread = _lru->_releaseOnMainThread;
+    pthread_mutex_unlock(&_lock);
+    return releaseOnMainThread;
+}
+
+- (void)setReleaseOnMainThread:(BOOL)releaseOnMainThread {
+    pthread_mutex_lock(&_lock);
+    _lru->_releaseOnMainThread = releaseOnMainThread;
+    pthread_mutex_unlock(&_lock);
+}
+
+- (BOOL)releaseAsynchronously {
+    pthread_mutex_lock(&_lock);
+    BOOL releaseAsynchronously = _lru->_releaseAsynchronously;
+    pthread_mutex_unlock(&_lock);
+    return releaseAsynchronously;
+}
+
+- (void)setReleaseAsynchronously:(BOOL)releaseAsynchronously {
+    pthread_mutex_lock(&_lock);
+    _lru->_releaseAsynchronously = releaseAsynchronously;
+    pthread_mutex_unlock(&_lock);
+}
+
+- (BOOL)containsObjectForKey:(id)key {
+    if (!key) return NO;
+    pthread_mutex_lock(&_lock);
+    BOOL contains = CFDictionaryContainsKey(_lru->_dic, (__bridge const void *)(key));
+    pthread_mutex_unlock(&_lock);
+    return contains;
+}
+
+- (id)objectForKey:(id)key {
+    if (!key) return nil;
+    pthread_mutex_lock(&_lock);
+    _YYLinkedMapNode *node = CFDictionaryGetValue(_lru->_dic, (__bridge const void *)(key));
+    if (node) {
+        node->_time = CACurrentMediaTime();
+        [_lru bringNodeToHead:node];
+    }
+    pthread_mutex_unlock(&_lock);
+    return node ? node->_value : nil;
+}
+
+- (void)setObject:(id)object forKey:(id)key {
+    [self setObject:object forKey:key withCost:0];
+}
+
+- (void)setObject:(id)object forKey:(id)key withCost:(NSUInteger)cost {
+    if (!key) return;
+    if (!object) {
+        [self removeObjectForKey:key];
+        return;
+    }
+    pthread_mutex_lock(&_lock);
+    _YYLinkedMapNode *node = CFDictionaryGetValue(_lru->_dic, (__bridge const void *)(key));
+    NSTimeInterval now = CACurrentMediaTime();
+    if (node) {
+        _lru->_totalCost -= node->_cost;
+        _lru->_totalCost += cost;
+        node->_cost = cost;
+        node->_time = now;
+        node->_value = object;
+        [_lru bringNodeToHead:node];
+    } else {
+        node = [_YYLinkedMapNode new];
+        node->_cost = cost;
+        node->_time = now;
+        node->_key = key;
+        node->_value = object;
+        [_lru insertNodeAtHead:node];
+    }
+    if (_lru->_totalCost > _costLimit) {
+        dispatch_async(_queue, ^{
+            [self trimToCost:_costLimit];
+        });
+    }
+    if (_lru->_totalCount > _countLimit) {
+        _YYLinkedMapNode *node = [_lru removeTailNode];
+        if (_lru->_releaseAsynchronously) {
+            dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
+            dispatch_async(queue, ^{
+                [node class]; //hold and release in queue
+            });
+        } else if (_lru->_releaseOnMainThread && !pthread_main_np()) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                [node class]; //hold and release in queue
+            });
+        }
+    }
+    pthread_mutex_unlock(&_lock);
+}
+
+- (void)removeObjectForKey:(id)key {
+    if (!key) return;
+    pthread_mutex_lock(&_lock);
+    _YYLinkedMapNode *node = CFDictionaryGetValue(_lru->_dic, (__bridge const void *)(key));
+    if (node) {
+        [_lru removeNode:node];
+        if (_lru->_releaseAsynchronously) {
+            dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
+            dispatch_async(queue, ^{
+                [node class]; //hold and release in queue
+            });
+        } else if (_lru->_releaseOnMainThread && !pthread_main_np()) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                [node class]; //hold and release in queue
+            });
+        }
+    }
+    pthread_mutex_unlock(&_lock);
+}
+
+- (void)removeAllObjects {
+    pthread_mutex_lock(&_lock);
+    [_lru removeAll];
+    pthread_mutex_unlock(&_lock);
+}
+
+- (void)trimToCount:(NSUInteger)count {
+    if (count == 0) {
+        [self removeAllObjects];
+        return;
+    }
+    [self _trimToCount:count];
+}
+
+- (void)trimToCost:(NSUInteger)cost {
+    [self _trimToCost:cost];
+}
+
+- (void)trimToAge:(NSTimeInterval)age {
+    [self _trimToAge:age];
+}
+
+- (NSString *)description {
+    if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _name];
+    else return [NSString stringWithFormat:@"<%@: %p>", self.class, self];
+}
+
+@end

+ 112 - 0
YYKit/Image/Categories/CALayer+YYWebImage.h

@@ -0,0 +1,112 @@
+//
+//  CALayer+YYWebImage.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+#import <QuartzCore/QuartzCore.h>
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYWebImageManager.h>
+#else
+#import "YYWebImageManager.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Web image methods for CALayer.
+ It will set image to layer.contents.
+ */
+@interface CALayer (YYWebImage)
+
+#pragma mark - image
+
+/**
+ Current image URL.
+ 
+ @discussion Set a new value to this property will cancel the previous request
+ operation and create a new request operation to fetch image. Set nil to clear
+ the image and image URL.
+ */
+@property (nullable, nonatomic, strong) NSURL *imageURL;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL The image url (remote or local file path).
+ @param options  The options to use when request the image.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder he image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param manager     The manager to create image request operation.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                   manager:(nullable YYWebImageManager *)manager
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Cancel the current image request.
+ */
+- (void)cancelCurrentImageRequest;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 189 - 0
YYKit/Image/Categories/CALayer+YYWebImage.m

@@ -0,0 +1,189 @@
+//
+//  CALayer+YYWebImage.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "CALayer+YYWebImage.h"
+#import "YYWebImageOperation.h"
+#import "_YYWebImageSetter.h"
+#import "YYKitMacro.h"
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(CALayer_YYWebImage)
+
+static int _YYWebImageSetterKey;
+
+
+@implementation CALayer (YYWebImage)
+
+- (NSURL *)imageURL {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    return setter.imageURL;
+}
+
+- (void)setImageURL:(NSURL *)imageURL {
+    [self setImageWithURL:imageURL
+              placeholder:nil
+                  options:kNilOptions
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:kNilOptions
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options {
+    [self setImageWithURL:imageURL
+              placeholder:nil
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:progress
+                transform:transform
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+                manager:(YYWebImageManager *)manager
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    
+    if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL];
+    manager = manager ? manager : [YYWebImageManager sharedManager];
+    
+    
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    if (!setter) {
+        setter = [_YYWebImageSetter new];
+        objc_setAssociatedObject(self, &_YYWebImageSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    int32_t sentinel = [setter cancelWithNewURL:imageURL];
+    
+    dispatch_async_on_main_queue(^{
+        if ((options & YYWebImageOptionSetImageWithFadeAnimation) &&
+            !(options & YYWebImageOptionAvoidSetImage)) {
+            [self removeAnimationForKey:_YYWebImageFadeAnimationKey];
+        }
+        
+        if (!imageURL) {
+            if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+                self.contents = (id)placeholder.CGImage;
+            }
+            return;
+        }
+        
+        // get the image from memory as quickly as possible
+        UIImage *imageFromMemory = nil;
+        if (manager.cache &&
+            !(options & YYWebImageOptionUseNSURLCache) &&
+            !(options & YYWebImageOptionRefreshImageCache)) {
+            imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory];
+        }
+        if (imageFromMemory) {
+            if (!(options & YYWebImageOptionAvoidSetImage)) {
+                self.contents = (id)imageFromMemory.CGImage;
+            }
+            if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil);
+            return;
+        }
+        
+        if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+            self.contents = (id)placeholder.CGImage;
+        }
+        
+        __weak typeof(self) _self = self;
+        dispatch_async([_YYWebImageSetter setterQueue], ^{
+            YYWebImageProgressBlock _progress = nil;
+            if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    progress(receivedSize, expectedSize);
+                });
+            };
+            
+            __block int32_t newSentinel = 0;
+            __block __weak typeof(setter) weakSetter = nil;
+            YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
+                __strong typeof(_self) self = _self;
+                BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage);
+                BOOL showFade = (options & YYWebImageOptionSetImageWithFadeAnimation);
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel;
+                    if (setImage && self && !sentinelChanged) {
+                        if (showFade) {
+                            CATransition *transition = [CATransition animation];
+                            transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime;
+                            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
+                            transition.type = kCATransitionFade;
+                            [self addAnimation:transition forKey:_YYWebImageFadeAnimationKey];
+                        }
+                        self.contents = (id)image.CGImage;
+                    }
+                    if (completion) {
+                        if (sentinelChanged) {
+                            completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil);
+                        } else {
+                            completion(image, url, from, stage, error);
+                        }
+                    }
+                });
+            };
+            
+            newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion];
+            weakSetter = setter;
+        });
+        
+        
+    });
+}
+
+- (void)cancelCurrentImageRequest {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    if (setter) [setter cancel];
+}
+
+@end

+ 109 - 0
YYKit/Image/Categories/MKAnnotationView+YYWebImage.h

@@ -0,0 +1,109 @@
+//
+//  MKAnnotationView+YYWebImage.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+#import <MapKit/MapKit.h>
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYWebImageManager.h>
+#else
+#import "YYWebImageManager.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Web image methods for MKAnnotationView.
+ */
+@interface MKAnnotationView (YYWebImage)
+
+/**
+ Current image URL.
+ 
+ @discussion Set a new value to this property will cancel the previous request
+ operation and create a new request operation to fetch image. Set nil to clear
+ the image and image URL.
+ */
+@property (nullable, nonatomic, strong) NSURL *imageURL;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL The image url (remote or local file path).
+ @param options  The options to use when request the image.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder he image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param manager     The manager to create image request operation.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                   manager:(nullable YYWebImageManager *)manager
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Cancel the current image request.
+ */
+- (void)cancelCurrentImageRequest;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 186 - 0
YYKit/Image/Categories/MKAnnotationView+YYWebImage.m

@@ -0,0 +1,186 @@
+//
+//  MKAnnotationView+YYWebImage.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "MKAnnotationView+YYWebImage.h"
+#import "YYWebImageOperation.h"
+#import "_YYWebImageSetter.h"
+#import "YYKitMacro.h"
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(MKAnnotationView_YYWebImage)
+
+static int _YYWebImageSetterKey;
+
+
+@implementation MKAnnotationView (YYWebImage)
+
+- (NSURL *)imageURL {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    return setter.imageURL;
+}
+
+- (void)setImageURL:(NSURL *)imageURL {
+    [self setImageWithURL:imageURL
+              placeholder:nil
+                  options:kNilOptions
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:kNilOptions
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options {
+    [self setImageWithURL:imageURL
+              placeholder:nil
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:progress
+                transform:transform
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+                manager:(YYWebImageManager *)manager
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL];
+    manager = manager ? manager : [YYWebImageManager sharedManager];
+    
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    if (!setter) {
+        setter = [_YYWebImageSetter new];
+        objc_setAssociatedObject(self, &_YYWebImageSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    int32_t sentinel = [setter cancelWithNewURL:imageURL];
+    
+    dispatch_async_on_main_queue(^{
+        if ((options & YYWebImageOptionSetImageWithFadeAnimation) &&
+            !(options & YYWebImageOptionAvoidSetImage)) {
+            if (!self.highlighted) {
+                [self.layer removeAnimationForKey:_YYWebImageFadeAnimationKey];
+            }
+        }
+        if (!imageURL) {
+            if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+                self.image = placeholder;
+            }
+            return;
+        }
+        
+        // get the image from memory as quickly as possible
+        UIImage *imageFromMemory = nil;
+        if (manager.cache &&
+            !(options & YYWebImageOptionUseNSURLCache) &&
+            !(options & YYWebImageOptionRefreshImageCache)) {
+            imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory];
+        }
+        if (imageFromMemory) {
+            if (!(options & YYWebImageOptionAvoidSetImage)) {
+                self.image = imageFromMemory;
+            }
+            if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil);
+            return;
+        }
+        
+        if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+            self.image = placeholder;
+        }
+        
+        __weak typeof(self) _self = self;
+        dispatch_async([_YYWebImageSetter setterQueue], ^{
+            YYWebImageProgressBlock _progress = nil;
+            if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    progress(receivedSize, expectedSize);
+                });
+            };
+            
+            __block int32_t newSentinel = 0;
+            __block __weak typeof(setter) weakSetter = nil;
+            YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
+                __strong typeof(_self) self = _self;
+                BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage);
+                BOOL showFade = ((options & YYWebImageOptionSetImageWithFadeAnimation) && !self.highlighted);
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel;
+                    if (setImage && self && !sentinelChanged) {
+                        if (showFade) {
+                            CATransition *transition = [CATransition animation];
+                            transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime;
+                            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
+                            transition.type = kCATransitionFade;
+                            [self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey];
+                        }
+                        self.image = image;
+                    }
+                    if (completion) {
+                        if (sentinelChanged) {
+                            completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil);
+                        } else {
+                            completion(image, url, from, stage, error);
+                        }
+                    }
+                });
+            };
+            
+            newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion];
+            weakSetter = setter;
+        });
+    });
+}
+
+- (void)cancelCurrentImageRequest {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    if (setter) [setter cancel];
+}
+
+@end

+ 213 - 0
YYKit/Image/Categories/UIButton+YYWebImage.h

@@ -0,0 +1,213 @@
+//
+//  UIButton+YYWebImage.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYWebImageManager.h>
+#else
+#import "YYWebImageManager.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Web image methods for UIButton.
+ */
+@interface UIButton (YYWebImage)
+
+#pragma mark - image
+
+/**
+ Current image URL for the specified state.
+ @return The image URL, or nil.
+ */
+- (nullable NSURL *)imageURLForState:(UIControlState)state;
+
+/**
+ Set the button's image with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+                  forState:(UIControlState)state
+               placeholder:(nullable UIImage *)placeholder;
+
+/**
+ Set the button's image with a specified URL for the specified state.
+ 
+ @param imageURL The image url (remote or local file path).
+ @param state    The state that uses the specified image.
+ @param options  The options to use when request the image.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+                  forState:(UIControlState)state
+                   options:(YYWebImageOptions)options;
+
+/**
+ Set the button's image with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+                  forState:(UIControlState)state
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the button's image with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+                  forState:(UIControlState)state
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the button's image with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param manager     The manager to create image request operation.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+                  forState:(UIControlState)state
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                   manager:(nullable YYWebImageManager *)manager
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Cancel the current image request for a specified state.
+ @param state The state that uses the specified image.
+ */
+- (void)cancelImageRequestForState:(UIControlState)state;
+
+
+
+#pragma mark - background image
+
+/**
+ Current backgroundImage URL for the specified state.
+ @return The image URL, or nil.
+ */
+- (nullable NSURL *)backgroundImageURLForState:(UIControlState)state;
+
+/**
+ Set the button's backgroundImage with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ */
+- (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL
+                            forState:(UIControlState)state
+                         placeholder:(nullable UIImage *)placeholder;
+
+/**
+ Set the button's backgroundImage with a specified URL for the specified state.
+ 
+ @param imageURL The image url (remote or local file path).
+ @param state    The state that uses the specified image.
+ @param options  The options to use when request the image.
+ */
+- (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL
+                            forState:(UIControlState)state
+                             options:(YYWebImageOptions)options;
+
+/**
+ Set the button's backgroundImage with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL
+                            forState:(UIControlState)state
+                         placeholder:(nullable UIImage *)placeholder
+                             options:(YYWebImageOptions)options
+                          completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the button's backgroundImage with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL
+                            forState:(UIControlState)state
+                         placeholder:(nullable UIImage *)placeholder
+                             options:(YYWebImageOptions)options
+                            progress:(nullable YYWebImageProgressBlock)progress
+                           transform:(nullable YYWebImageTransformBlock)transform
+                          completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the button's backgroundImage with a specified URL for the specified state.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param state       The state that uses the specified image.
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param manager     The manager to create image request operation.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL
+                            forState:(UIControlState)state
+                         placeholder:(nullable UIImage *)placeholder
+                             options:(YYWebImageOptions)options
+                             manager:(nullable YYWebImageManager *)manager
+                            progress:(nullable YYWebImageProgressBlock)progress
+                           transform:(nullable YYWebImageTransformBlock)transform
+                          completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Cancel the current backgroundImage request for a specified state.
+ @param state The state that uses the specified image.
+ */
+- (void)cancelBackgroundImageRequestForState:(UIControlState)state;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 430 - 0
YYKit/Image/Categories/UIButton+YYWebImage.m

@@ -0,0 +1,430 @@
+//
+//  UIButton+YYWebImage.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIButton+YYWebImage.h"
+#import "YYWebImageOperation.h"
+#import "_YYWebImageSetter.h"
+#import "YYKitMacro.h"
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(UIButton_YYWebImage)
+
+static inline NSNumber *UIControlStateSingle(UIControlState state) {
+    if (state & UIControlStateHighlighted) return @(UIControlStateHighlighted);
+    if (state & UIControlStateDisabled) return @(UIControlStateDisabled);
+    if (state & UIControlStateSelected) return @(UIControlStateSelected);
+    return @(UIControlStateNormal);
+}
+
+static inline NSArray *UIControlStateMulti(UIControlState state) {
+    NSMutableArray *array = [NSMutableArray new];
+    if (state & UIControlStateHighlighted) [array addObject:@(UIControlStateHighlighted)];
+    if (state & UIControlStateDisabled) [array addObject:@(UIControlStateDisabled)];
+    if (state & UIControlStateSelected) [array addObject:@(UIControlStateSelected)];
+    if ((state & 0xFF) == 0) [array addObject:@(UIControlStateNormal)];
+    return array;
+}
+
+static int _YYWebImageSetterKey;
+static int _YYWebImageBackgroundSetterKey;
+
+
+@interface _YYWebImageSetterDicForButton : NSObject
+- (_YYWebImageSetter *)setterForState:(NSNumber *)state;
+- (_YYWebImageSetter *)lazySetterForState:(NSNumber *)state;
+@end
+
+@implementation _YYWebImageSetterDicForButton {
+    NSMutableDictionary *_dic;
+    dispatch_semaphore_t _lock;
+}
+- (instancetype)init {
+    self = [super init];
+    _lock = dispatch_semaphore_create(1);
+    _dic = [NSMutableDictionary new];
+    return self;
+}
+- (_YYWebImageSetter *)setterForState:(NSNumber *)state {
+    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
+    _YYWebImageSetter *setter = _dic[state];
+    dispatch_semaphore_signal(_lock);
+    return setter;
+    
+}
+- (_YYWebImageSetter *)lazySetterForState:(NSNumber *)state {
+    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
+    _YYWebImageSetter *setter = _dic[state];
+    if (!setter) {
+        setter = [_YYWebImageSetter new];
+        _dic[state] = setter;
+    }
+    dispatch_semaphore_signal(_lock);
+    return setter;
+}
+@end
+
+
+@implementation UIButton (YYWebImage)
+
+#pragma mark - image
+
+- (void)_setImageWithURL:(NSURL *)imageURL
+          forSingleState:(NSNumber *)state
+             placeholder:(UIImage *)placeholder
+                 options:(YYWebImageOptions)options
+                 manager:(YYWebImageManager *)manager
+                progress:(YYWebImageProgressBlock)progress
+               transform:(YYWebImageTransformBlock)transform
+              completion:(YYWebImageCompletionBlock)completion {
+    if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL];
+    manager = manager ? manager : [YYWebImageManager sharedManager];
+    
+    _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    if (!dic) {
+        dic = [_YYWebImageSetterDicForButton new];
+        objc_setAssociatedObject(self, &_YYWebImageSetterKey, dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    _YYWebImageSetter *setter = [dic lazySetterForState:state];
+    int32_t sentinel = [setter cancelWithNewURL:imageURL];
+    
+    dispatch_async_on_main_queue(^{
+        if (!imageURL) {
+            if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+                [self setImage:placeholder forState:state.integerValue];
+            }
+            return;
+        }
+        
+        // get the image from memory as quickly as possible
+        UIImage *imageFromMemory = nil;
+        if (manager.cache &&
+            !(options & YYWebImageOptionUseNSURLCache) &&
+            !(options & YYWebImageOptionRefreshImageCache)) {
+            imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory];
+        }
+        if (imageFromMemory) {
+            if (!(options & YYWebImageOptionAvoidSetImage)) {
+                [self setImage:imageFromMemory forState:state.integerValue];
+            }
+            if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil);
+            return;
+        }
+        
+        
+        if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+            [self setImage:placeholder forState:state.integerValue];
+        }
+        
+        __weak typeof(self) _self = self;
+        dispatch_async([_YYWebImageSetter setterQueue], ^{
+            YYWebImageProgressBlock _progress = nil;
+            if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    progress(receivedSize, expectedSize);
+                });
+            };
+            
+            __block int32_t newSentinel = 0;
+            __block __weak typeof(setter) weakSetter = nil;
+            YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
+                __strong typeof(_self) self = _self;
+                BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage);
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel;
+                    if (setImage && self && !sentinelChanged) {
+                        [self setImage:image forState:state.integerValue];
+                    }
+                    if (completion) {
+                        if (sentinelChanged) {
+                            completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil);
+                        } else {
+                            completion(image, url, from, stage, error);
+                        }
+                    }
+                });
+            };
+            
+            newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion];
+            weakSetter = setter;
+        });
+    });
+}
+
+- (void)_cancelImageRequestForSingleState:(NSNumber *)state {
+    _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    _YYWebImageSetter *setter = [dic setterForState:state];
+    if (setter) [setter cancel];
+}
+
+- (NSURL *)imageURLForState:(UIControlState)state {
+    _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    _YYWebImageSetter *setter = [dic setterForState:UIControlStateSingle(state)];
+    return setter.imageURL;
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder {
+    [self setImageWithURL:imageURL
+                 forState:state
+              placeholder:placeholder
+                  options:kNilOptions
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL forState:(UIControlState)state options:(YYWebImageOptions)options {
+    [self setImageWithURL:imageURL
+                 forState:state
+              placeholder:nil
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+               forState:(UIControlState)state
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+                 forState:state
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+               forState:(UIControlState)state
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+                 forState:state
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:progress
+                transform:transform
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+               forState:(UIControlState)state
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+                manager:(YYWebImageManager *)manager
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    for (NSNumber *num in UIControlStateMulti(state)) {
+        [self _setImageWithURL:imageURL
+                forSingleState:num
+                   placeholder:placeholder
+                       options:options
+                       manager:manager
+                      progress:progress
+                     transform:transform
+                    completion:completion];
+    }
+}
+
+- (void)cancelImageRequestForState:(UIControlState)state {
+    for (NSNumber *num in UIControlStateMulti(state)) {
+        [self _cancelImageRequestForSingleState:num];
+    }
+}
+
+
+#pragma mark - background image
+
+- (void)_setBackgroundImageWithURL:(NSURL *)imageURL
+                    forSingleState:(NSNumber *)state
+                       placeholder:(UIImage *)placeholder
+                           options:(YYWebImageOptions)options
+                           manager:(YYWebImageManager *)manager
+                          progress:(YYWebImageProgressBlock)progress
+                         transform:(YYWebImageTransformBlock)transform
+                        completion:(YYWebImageCompletionBlock)completion {
+    if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL];
+    manager = manager ? manager : [YYWebImageManager sharedManager];
+    
+    _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageBackgroundSetterKey);
+    if (!dic) {
+        dic = [_YYWebImageSetterDicForButton new];
+        objc_setAssociatedObject(self, &_YYWebImageBackgroundSetterKey, dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    _YYWebImageSetter *setter = [dic lazySetterForState:state];
+    int32_t sentinel = [setter cancelWithNewURL:imageURL];
+    
+    dispatch_async_on_main_queue(^{
+        if (!imageURL) {
+            if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+                [self setBackgroundImage:placeholder forState:state.integerValue];
+            }
+            return;
+        }
+        
+        // get the image from memory as quickly as possible
+        UIImage *imageFromMemory = nil;
+        if (manager.cache &&
+            !(options & YYWebImageOptionUseNSURLCache) &&
+            !(options & YYWebImageOptionRefreshImageCache)) {
+            imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory];
+        }
+        if (imageFromMemory) {
+            if (!(options & YYWebImageOptionAvoidSetImage)) {
+                [self setBackgroundImage:imageFromMemory forState:state.integerValue];
+            }
+            if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil);
+            return;
+        }
+        
+        
+        if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+            [self setBackgroundImage:placeholder forState:state.integerValue];
+        }
+        
+        __weak typeof(self) _self = self;
+        dispatch_async([_YYWebImageSetter setterQueue], ^{
+            YYWebImageProgressBlock _progress = nil;
+            if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    progress(receivedSize, expectedSize);
+                });
+            };
+            
+            __block int32_t newSentinel = 0;
+            __block __weak typeof(setter) weakSetter = nil;
+            YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
+                __strong typeof(_self) self = _self;
+                BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage);
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel;
+                    if (setImage && self && !sentinelChanged) {
+                        [self setBackgroundImage:image forState:state.integerValue];
+                    }
+                    if (completion) {
+                        if (sentinelChanged) {
+                            completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil);
+                        } else {
+                            completion(image, url, from, stage, error);
+                        }
+                    }
+                });
+            };
+            
+            newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion];
+            weakSetter = setter;
+        });
+    });
+}
+
+- (void)_cancelBackgroundImageRequestForSingleState:(NSNumber *)state {
+    _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageBackgroundSetterKey);
+    _YYWebImageSetter *setter = [dic setterForState:state];
+    if (setter) [setter cancel];
+}
+
+- (NSURL *)backgroundImageURLForState:(UIControlState)state {
+    _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageBackgroundSetterKey);
+    _YYWebImageSetter *setter = [dic setterForState:UIControlStateSingle(state)];
+    return setter.imageURL;
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder {
+    [self setBackgroundImageWithURL:imageURL
+                           forState:state
+                        placeholder:placeholder
+                            options:kNilOptions
+                            manager:nil
+                           progress:nil
+                          transform:nil
+                         completion:nil];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)imageURL forState:(UIControlState)state options:(YYWebImageOptions)options {
+    [self setBackgroundImageWithURL:imageURL
+                           forState:state
+                        placeholder:nil
+                            options:options
+                            manager:nil
+                           progress:nil
+                          transform:nil
+                         completion:nil];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)imageURL
+               forState:(UIControlState)state
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setBackgroundImageWithURL:imageURL
+                           forState:state
+                        placeholder:placeholder
+                            options:options
+                            manager:nil
+                           progress:nil
+                          transform:nil
+                         completion:completion];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)imageURL
+               forState:(UIControlState)state
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setBackgroundImageWithURL:imageURL
+                           forState:state
+                        placeholder:placeholder
+                            options:options
+                            manager:nil
+                           progress:progress
+                          transform:transform
+                         completion:completion];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)imageURL
+               forState:(UIControlState)state
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+                manager:(YYWebImageManager *)manager
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    for (NSNumber *num in UIControlStateMulti(state)) {
+        [self _setBackgroundImageWithURL:imageURL
+                          forSingleState:num
+                             placeholder:placeholder
+                                 options:options
+                                 manager:manager
+                                progress:progress
+                               transform:transform
+                              completion:completion];
+    }
+}
+
+- (void)cancelBackgroundImageRequestForState:(UIControlState)state {
+    for (NSNumber *num in UIControlStateMulti(state)) {
+        [self _cancelBackgroundImageRequestForSingleState:num];
+    }
+}
+
+@end

+ 193 - 0
YYKit/Image/Categories/UIImageView+YYWebImage.h

@@ -0,0 +1,193 @@
+//
+//  UIImageView+YYWebImage.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYWebImageManager.h>
+#else
+#import "YYWebImageManager.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Web image methods for UIImageView.
+ */
+@interface UIImageView (YYWebImage)
+
+#pragma mark - image
+
+/**
+ Current image URL.
+ 
+ @discussion Set a new value to this property will cancel the previous request 
+ operation and create a new request operation to fetch image. Set nil to clear 
+ the image and image URL.
+ */
+@property (nullable, nonatomic, strong) NSURL *imageURL;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL The image url (remote or local file path).
+ @param options  The options to use when request the image.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `image` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder he image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param manager     The manager to create image request operation.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setImageWithURL:(nullable NSURL *)imageURL
+               placeholder:(nullable UIImage *)placeholder
+                   options:(YYWebImageOptions)options
+                   manager:(nullable YYWebImageManager *)manager
+                  progress:(nullable YYWebImageProgressBlock)progress
+                 transform:(nullable YYWebImageTransformBlock)transform
+                completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Cancel the current image request.
+ */
+- (void)cancelCurrentImageRequest;
+
+
+
+#pragma mark - highlight image
+
+/**
+ Current highlighted image URL.
+ 
+ @discussion Set a new value to this property will cancel the previous request
+ operation and create a new request operation to fetch image. Set nil to clear
+ the highlighted image and image URL.
+ */
+@property (nullable, nonatomic, strong) NSURL *highlightedImageURL;
+
+/**
+ Set the view's `highlightedImage` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ */
+- (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder;
+
+/**
+ Set the view's `highlightedImage` with a specified URL.
+ 
+ @param imageURL The image url (remote or local file path).
+ @param options  The options to use when request the image.
+ */
+- (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options;
+
+/**
+ Set the view's `highlightedImage` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL
+                          placeholder:(nullable UIImage *)placeholder
+                              options:(YYWebImageOptions)options
+                           completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `highlightedImage` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder The image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL
+                          placeholder:(nullable UIImage *)placeholder
+                              options:(YYWebImageOptions)options
+                             progress:(nullable YYWebImageProgressBlock)progress
+                            transform:(nullable YYWebImageTransformBlock)transform
+                           completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Set the view's `highlightedImage` with a specified URL.
+ 
+ @param imageURL    The image url (remote or local file path).
+ @param placeholder he image to be set initially, until the image request finishes.
+ @param options     The options to use when request the image.
+ @param manager     The manager to create image request operation.
+ @param progress    The block invoked (on main thread) during image request.
+ @param transform   The block invoked (on background thread) to do additional image process.
+ @param completion  The block invoked (on main thread) when image request completed.
+ */
+- (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL
+                          placeholder:(nullable UIImage *)placeholder
+                              options:(YYWebImageOptions)options
+                              manager:(nullable YYWebImageManager *)manager
+                             progress:(nullable YYWebImageProgressBlock)progress
+                            transform:(nullable YYWebImageTransformBlock)transform
+                           completion:(nullable YYWebImageCompletionBlock)completion;
+
+/**
+ Cancel the current highlighed image request.
+ */
+- (void)cancelCurrentHighlightedImageRequest;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 358 - 0
YYKit/Image/Categories/UIImageView+YYWebImage.m

@@ -0,0 +1,358 @@
+//
+//  UIImageView+YYWebImage.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/23.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "UIImageView+YYWebImage.h"
+#import "YYWebImageOperation.h"
+#import "_YYWebImageSetter.h"
+#import "YYKitMacro.h"
+#import <objc/runtime.h>
+
+YYSYNTH_DUMMY_CLASS(UIImageView_YYWebImage)
+
+static int _YYWebImageSetterKey;
+static int _YYWebImageHighlightedSetterKey;
+
+
+@implementation UIImageView (YYWebImage)
+
+#pragma mark - image
+
+- (NSURL *)imageURL {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    return setter.imageURL;
+}
+
+/*
+ "setImageWithURL" is conflict to AFNetworking and SDWebImage...WTF!
+ So.. We use "setImageURL:" instead.
+ */
+- (void)setImageURL:(NSURL *)imageURL {
+    [self setImageWithURL:imageURL
+              placeholder:nil
+                  options:kNilOptions
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:kNilOptions
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options {
+    [self setImageWithURL:imageURL
+              placeholder:nil
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:nil
+                transform:nil
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    [self setImageWithURL:imageURL
+              placeholder:placeholder
+                  options:options
+                  manager:nil
+                 progress:progress
+                transform:transform
+               completion:completion];
+}
+
+- (void)setImageWithURL:(NSURL *)imageURL
+            placeholder:(UIImage *)placeholder
+                options:(YYWebImageOptions)options
+                manager:(YYWebImageManager *)manager
+               progress:(YYWebImageProgressBlock)progress
+              transform:(YYWebImageTransformBlock)transform
+             completion:(YYWebImageCompletionBlock)completion {
+    if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL];
+    manager = manager ? manager : [YYWebImageManager sharedManager];
+    
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    if (!setter) {
+        setter = [_YYWebImageSetter new];
+        objc_setAssociatedObject(self, &_YYWebImageSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    int32_t sentinel = [setter cancelWithNewURL:imageURL];
+    
+    dispatch_async_on_main_queue(^{
+        if ((options & YYWebImageOptionSetImageWithFadeAnimation) &&
+            !(options & YYWebImageOptionAvoidSetImage)) {
+            if (!self.highlighted) {
+                [self.layer removeAnimationForKey:_YYWebImageFadeAnimationKey];
+            }
+        }
+        
+        if (!imageURL) {
+            if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+                self.image = placeholder;
+            }
+            return;
+        }
+        
+        // get the image from memory as quickly as possible
+        UIImage *imageFromMemory = nil;
+        if (manager.cache &&
+            !(options & YYWebImageOptionUseNSURLCache) &&
+            !(options & YYWebImageOptionRefreshImageCache)) {
+            imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory];
+        }
+        if (imageFromMemory) {
+            if (!(options & YYWebImageOptionAvoidSetImage)) {
+                self.image = imageFromMemory;
+            }
+            if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil);
+            return;
+        }
+        
+        if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+            self.image = placeholder;
+        }
+        
+        __weak typeof(self) _self = self;
+        dispatch_async([_YYWebImageSetter setterQueue], ^{
+            YYWebImageProgressBlock _progress = nil;
+            if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    progress(receivedSize, expectedSize);
+                });
+            };
+            
+            __block int32_t newSentinel = 0;
+            __block __weak typeof(setter) weakSetter = nil;
+            YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
+                __strong typeof(_self) self = _self;
+                BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage);
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel;
+                    if (setImage && self && !sentinelChanged) {
+                        BOOL showFade = ((options & YYWebImageOptionSetImageWithFadeAnimation) && !self.highlighted);
+                        if (showFade) {
+                            CATransition *transition = [CATransition animation];
+                            transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime;
+                            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
+                            transition.type = kCATransitionFade;
+                            [self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey];
+                        }
+                        self.image = image;
+                    }
+                    if (completion) {
+                        if (sentinelChanged) {
+                            completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil);
+                        } else {
+                            completion(image, url, from, stage, error);
+                        }
+                    }
+                });
+            };
+            
+            newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion];
+            weakSetter = setter;
+        });
+    });
+}
+
+- (void)cancelCurrentImageRequest {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
+    if (setter) [setter cancel];
+}
+
+
+#pragma mark - highlighted image
+
+- (NSURL *)highlightedImageURL {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageHighlightedSetterKey);
+    return setter.imageURL;
+}
+
+- (void)setHighlightedImageURL:(NSURL *)imageURL {
+    [self setHighlightedImageWithURL:imageURL
+                         placeholder:nil
+                             options:kNilOptions
+                             manager:nil
+                            progress:nil
+                           transform:nil
+                          completion:nil];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder {
+    [self setHighlightedImageWithURL:imageURL
+                         placeholder:placeholder
+                             options:kNilOptions
+                             manager:nil
+                            progress:nil
+                           transform:nil
+                          completion:nil];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options {
+    [self setHighlightedImageWithURL:imageURL
+                         placeholder:nil
+                             options:options
+                             manager:nil
+                            progress:nil
+                           transform:nil
+                          completion:nil];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)imageURL
+                       placeholder:(UIImage *)placeholder
+                           options:(YYWebImageOptions)options
+                        completion:(YYWebImageCompletionBlock)completion {
+    [self setHighlightedImageWithURL:imageURL
+                         placeholder:placeholder
+                             options:options
+                             manager:nil
+                            progress:nil
+                           transform:nil
+                          completion:completion];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)imageURL
+                       placeholder:(UIImage *)placeholder
+                           options:(YYWebImageOptions)options
+                          progress:(YYWebImageProgressBlock)progress
+                         transform:(YYWebImageTransformBlock)transform
+                        completion:(YYWebImageCompletionBlock)completion {
+    [self setHighlightedImageWithURL:imageURL
+                         placeholder:placeholder
+                             options:options
+                             manager:nil
+                            progress:progress
+                           transform:nil
+                          completion:completion];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)imageURL
+                       placeholder:(UIImage *)placeholder
+                           options:(YYWebImageOptions)options
+                           manager:(YYWebImageManager *)manager
+                          progress:(YYWebImageProgressBlock)progress
+                         transform:(YYWebImageTransformBlock)transform
+                        completion:(YYWebImageCompletionBlock)completion {
+    if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL];
+    manager = manager ? manager : [YYWebImageManager sharedManager];
+    
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageHighlightedSetterKey);
+    if (!setter) {
+        setter = [_YYWebImageSetter new];
+        objc_setAssociatedObject(self, &_YYWebImageHighlightedSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    int32_t sentinel = [setter cancelWithNewURL:imageURL];
+    
+    dispatch_async_on_main_queue(^{
+        if ((options & YYWebImageOptionSetImageWithFadeAnimation) &&
+            !(options & YYWebImageOptionAvoidSetImage)) {
+            if (self.highlighted) {
+                [self.layer removeAnimationForKey:_YYWebImageFadeAnimationKey];
+            }
+        }
+        if (!imageURL) {
+            if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+                self.highlightedImage = placeholder;
+            }
+            return;
+        }
+        
+        // get the image from memory as quickly as possible
+        UIImage *imageFromMemory = nil;
+        if (manager.cache &&
+            !(options & YYWebImageOptionUseNSURLCache) &&
+            !(options & YYWebImageOptionRefreshImageCache)) {
+            imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory];
+        }
+        if (imageFromMemory) {
+            if (!(options & YYWebImageOptionAvoidSetImage)) {
+                self.highlightedImage = imageFromMemory;
+            }
+            if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil);
+            return;
+        }
+        
+        if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
+            self.highlightedImage = placeholder;
+        }
+        
+        __weak typeof(self) _self = self;
+        dispatch_async([_YYWebImageSetter setterQueue], ^{
+            YYWebImageProgressBlock _progress = nil;
+            if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    progress(receivedSize, expectedSize);
+                });
+            };
+            
+            __block int32_t newSentinel = 0;
+            __block __weak typeof(setter) weakSetter = nil;
+            YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
+                __strong typeof(_self) self = _self;
+                BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage);
+                BOOL showFade = ((options & YYWebImageOptionSetImageWithFadeAnimation) && self.highlighted);
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel;
+                    if (setImage && self && !sentinelChanged) {
+                        if (showFade) {
+                            CATransition *transition = [CATransition animation];
+                            transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime;
+                            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
+                            transition.type = kCATransitionFade;
+                            [self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey];
+                        }
+                        self.highlightedImage = image;
+                    }
+                    if (completion) {
+                        if (sentinelChanged) {
+                            completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil);
+                        } else {
+                            completion(image, url, from, stage, error);
+                        }
+                    }
+                });
+            };
+            
+            newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion];
+            weakSetter = setter;
+        });
+    });
+}
+
+- (void)cancelCurrentHighlightedImageRequest {
+    _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageHighlightedSetterKey);
+    if (setter) [setter cancel];
+}
+
+@end

+ 54 - 0
YYKit/Image/Categories/_YYWebImageSetter.h

@@ -0,0 +1,54 @@
+//
+//  _YYWebImageSetter.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/7/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYWebImageManager.h>
+#else
+#import "YYWebImageManager.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+extern NSString *const _YYWebImageFadeAnimationKey;
+extern const NSTimeInterval _YYWebImageFadeTime;
+extern const NSTimeInterval _YYWebImageProgressiveFadeTime;
+
+/**
+ Private class used by web image categories.
+ Typically, you should not use this class directly.
+ */
+@interface _YYWebImageSetter : NSObject
+/// Current image url.
+@property (nullable, nonatomic, readonly) NSURL *imageURL;
+/// Current sentinel.
+@property (nonatomic, readonly) int32_t sentinel;
+
+/// Create new operation for web image and return a sentinel value.
+- (int32_t)setOperationWithSentinel:(int32_t)sentinel
+                                url:(nullable NSURL *)imageURL
+                            options:(YYWebImageOptions)options
+                            manager:(YYWebImageManager *)manager
+                           progress:(nullable YYWebImageProgressBlock)progress
+                          transform:(nullable YYWebImageTransformBlock)transform
+                         completion:(nullable YYWebImageCompletionBlock)completion;
+
+/// Cancel and return a sentinel value. The imageURL will be set to nil.
+- (int32_t)cancel;
+
+/// Cancel and return a sentinel value. The imageURL will be set to new value.
+- (int32_t)cancelWithNewURL:(nullable NSURL *)imageURL;
+
+/// A queue to set operation.
++ (dispatch_queue_t)setterQueue;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 103 - 0
YYKit/Image/Categories/_YYWebImageSetter.m

@@ -0,0 +1,103 @@
+//
+//  _YYWebImageSetter.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/7/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "_YYWebImageSetter.h"
+#import "YYWebImageOperation.h"
+#import <libkern/OSAtomic.h>
+
+NSString *const _YYWebImageFadeAnimationKey = @"YYWebImageFade";
+const NSTimeInterval _YYWebImageFadeTime = 0.2;
+const NSTimeInterval _YYWebImageProgressiveFadeTime = 0.4;
+
+
+@implementation _YYWebImageSetter {
+    dispatch_semaphore_t _lock;
+    NSURL *_imageURL;
+    NSOperation *_operation;
+    int32_t _sentinel;
+}
+
+- (instancetype)init {
+    self = [super init];
+    _lock = dispatch_semaphore_create(1);
+    return self;
+}
+
+- (NSURL *)imageURL {
+    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
+    NSURL *imageURL = _imageURL;
+    dispatch_semaphore_signal(_lock);
+    return imageURL;
+}
+
+- (void)dealloc {
+    OSAtomicIncrement32(&_sentinel);
+    [_operation cancel];
+}
+
+- (int32_t)setOperationWithSentinel:(int32_t)sentinel
+                                url:(NSURL *)imageURL
+                            options:(YYWebImageOptions)options
+                            manager:(YYWebImageManager *)manager
+                           progress:(YYWebImageProgressBlock)progress
+                          transform:(YYWebImageTransformBlock)transform
+                         completion:(YYWebImageCompletionBlock)completion {
+    if (sentinel != _sentinel) {
+        if (completion) completion(nil, imageURL, YYWebImageFromNone, YYWebImageStageCancelled, nil);
+        return _sentinel;
+    }
+    
+    NSOperation *operation = [manager requestImageWithURL:imageURL options:options progress:progress transform:transform completion:completion];
+    if (!operation && completion) {
+        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"YYWebImageOperation create failed." };
+        completion(nil, imageURL, YYWebImageFromNone, YYWebImageStageFinished, [NSError errorWithDomain:@"com.ibireme.yykit.webimage" code:-1 userInfo:userInfo]);
+    }
+    
+    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
+    if (sentinel == _sentinel) {
+        if (_operation) [_operation cancel];
+        _operation = operation;
+        sentinel = OSAtomicIncrement32(&_sentinel);
+    } else {
+        [operation cancel];
+    }
+    dispatch_semaphore_signal(_lock);
+    return sentinel;
+}
+
+- (int32_t)cancel {
+    return [self cancelWithNewURL:nil];
+}
+
+- (int32_t)cancelWithNewURL:(NSURL *)imageURL {
+    int32_t sentinel;
+    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
+    if (_operation) {
+        [_operation cancel];
+        _operation = nil;
+    }
+    _imageURL = imageURL;
+    sentinel = OSAtomicIncrement32(&_sentinel);
+    dispatch_semaphore_signal(_lock);
+    return sentinel;
+}
+
++ (dispatch_queue_t)setterQueue {
+    static dispatch_queue_t queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        queue = dispatch_queue_create("com.ibireme.yykit.webimage.setter", DISPATCH_QUEUE_SERIAL);
+        dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
+    });
+    return queue;
+}
+
+@end

+ 125 - 0
YYKit/Image/YYAnimatedImageView.h

@@ -0,0 +1,125 @@
+//
+//  YYAnimatedImageView.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/19.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ An image view for displaying animated image.
+ 
+ @discussion It is a fully compatible `UIImageView` subclass.
+ If the `image` or `highlightedImage` property adopt to the `YYAnimatedImage` protocol,
+ then it can be used to play the multi-frame animation. The animation can also be 
+ controlled with the UIImageView methods `-startAnimating`, `-stopAnimating` and `-isAnimating`.
+ 
+ This view request the frame data just in time. When the device has enough free memory, 
+ this view may cache some or all future frames in an inner buffer for lower CPU cost.
+ Buffer size is dynamically adjusted based on the current state of the device memory.
+ 
+ Sample Code:
+ 
+     // ani@3x.gif
+     YYImage *image = [YYImage imageNamed:@"ani"];
+     YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image];
+     [view addSubView:imageView];
+ */
+@interface YYAnimatedImageView : UIImageView
+
+/**
+ If the image has more than one frame, set this value to `YES` will automatically 
+ play/stop the animation when the view become visible/invisible.
+ 
+ The default value is `YES`.
+ */
+@property (nonatomic) BOOL autoPlayAnimatedImage;
+
+/**
+ Index of the currently displayed frame (index from 0).
+ 
+ Set a new value to this property will cause to display the new frame immediately.
+ If the new value is invalid, this method has no effect.
+ 
+ You can add an observer to this property to observe the playing status.
+ */
+@property (nonatomic) NSUInteger currentAnimatedImageIndex;
+
+/**
+ Whether the image view is playing animation currently.
+ 
+ You can add an observer to this property to observe the playing status.
+ */
+@property (nonatomic, readonly) BOOL currentIsPlayingAnimation;
+
+/**
+ The animation timer's runloop mode, default is `NSRunLoopCommonModes`.
+ 
+ Set this property to `NSDefaultRunLoopMode` will make the animation pause during
+ UIScrollView scrolling.
+ */
+@property (nonatomic, copy) NSString *runloopMode;
+
+/**
+ The max size (in bytes) for inner frame buffer size, default is 0 (dynamically).
+ 
+ When the device has enough free memory, this view will request and decode some or 
+ all future frame image into an inner buffer. If this property's value is 0, then 
+ the max buffer size will be dynamically adjusted based on the current state of 
+ the device free memory. Otherwise, the buffer size will be limited by this value.
+ 
+ When receive memory warning or app enter background, the buffer will be released 
+ immediately, and may grow back at the right time.
+ */
+@property (nonatomic) NSUInteger maxBufferSize;
+
+@end
+
+
+
+/**
+ The YYAnimatedImage protocol declares the required methods for animated image
+ display with YYAnimatedImageView.
+ 
+ Subclass a UIImage and implement this protocol, so that instances of that class 
+ can be set to YYAnimatedImageView.image or YYAnimatedImageView.highlightedImage
+ to display animation.
+ 
+ See `YYImage` and `YYFrameImage` for example.
+ */
+@protocol YYAnimatedImage <NSObject>
+@required
+/// Total animated frame count.
+/// If the frame count is less than 1, then the methods below will be ignored.
+- (NSUInteger)animatedImageFrameCount;
+
+/// Animation loop count, 0 means infinite looping.
+- (NSUInteger)animatedImageLoopCount;
+
+/// Bytes per frame (in memory). It may used to optimize memory buffer size.
+- (NSUInteger)animatedImageBytesPerFrame;
+
+/// Returns the frame image from a specified index.
+/// This method may be called on background thread.
+/// @param index  Frame index (zero based).
+- (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index;
+
+/// Returns the frames's duration from a specified index.
+/// @param index  Frame index (zero based).
+- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index;
+
+@optional
+/// A rectangle in image coordinates defining the subrectangle of the image that
+/// will be displayed. The rectangle should not outside the image's bounds.
+/// It may used to display sprite animation with a single image (sprite sheet).
+- (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index;
+@end
+
+NS_ASSUME_NONNULL_END

+ 578 - 0
YYKit/Image/YYAnimatedImageView.m

@@ -0,0 +1,578 @@
+//
+//  YYAnimatedImageView.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/19.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYAnimatedImageView.h"
+#import "YYWeakProxy.h"
+#import "UIDevice+YYAdd.h"
+#import "YYImageCoder.h"
+#import "YYKitMacro.h"
+
+#define BUFFER_SIZE (10 * 1024 * 1024) // 10MB (minimum memory buffer size)
+
+#define LOCK(...) dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER); \
+__VA_ARGS__; \
+dispatch_semaphore_signal(self->_lock);
+
+#define LOCK_VIEW(...) dispatch_semaphore_wait(view->_lock, DISPATCH_TIME_FOREVER); \
+__VA_ARGS__; \
+dispatch_semaphore_signal(view->_lock);
+
+
+typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
+    YYAnimatedImageTypeNone = 0,
+    YYAnimatedImageTypeImage,
+    YYAnimatedImageTypeHighlightedImage,
+    YYAnimatedImageTypeImages,
+    YYAnimatedImageTypeHighlightedImages,
+};
+
+@interface YYAnimatedImageView() {
+    @package
+    UIImage <YYAnimatedImage> *_curAnimatedImage;
+    
+    dispatch_once_t _onceToken;
+    dispatch_semaphore_t _lock; ///< lock for _buffer
+    NSOperationQueue *_requestQueue; ///< image request queue, serial
+    
+    CADisplayLink *_link; ///< ticker for change frame
+    NSTimeInterval _time; ///< time after last frame
+    
+    UIImage *_curFrame; ///< current frame to display
+    NSUInteger _curIndex; ///< current frame index (from 0)
+    NSUInteger _totalFrameCount; ///< total frame count
+    
+    BOOL _loopEnd; ///< whether the loop is end.
+    NSUInteger _curLoop; ///< current loop count (from 0)
+    NSUInteger _totalLoop; ///< total loop count, 0 means infinity
+    
+    NSMutableDictionary *_buffer; ///< frame buffer
+    BOOL _bufferMiss; ///< whether miss frame on last opportunity
+    NSUInteger _maxBufferCount; ///< maximum buffer count
+    NSInteger _incrBufferCount; ///< current allowed buffer count (will increase by step)
+    
+    CGRect _curContentsRect;
+    BOOL _curImageHasContentsRect; ///< image has implementated "animatedImageContentsRectAtIndex:"
+}
+@property (nonatomic, readwrite) BOOL currentIsPlayingAnimation;
+- (void)calcMaxBufferCount;
+@end
+
+/// An operation for image fetch
+@interface _YYAnimatedImageViewFetchOperation : NSOperation
+@property (nonatomic, weak) YYAnimatedImageView *view;
+@property (nonatomic, assign) NSUInteger nextIndex;
+@property (nonatomic, strong) UIImage <YYAnimatedImage> *curImage;
+@end
+
+@implementation _YYAnimatedImageViewFetchOperation
+- (void)main {
+    __strong YYAnimatedImageView *view = _view;
+    if (!view) return;
+    if ([self isCancelled]) return;
+    view->_incrBufferCount++;
+    if (view->_incrBufferCount == 0) [view calcMaxBufferCount];
+    if (view->_incrBufferCount > (NSInteger)view->_maxBufferCount) {
+        view->_incrBufferCount = view->_maxBufferCount;
+    }
+    NSUInteger idx = _nextIndex;
+    NSUInteger max = view->_incrBufferCount < 1 ? 1 : view->_incrBufferCount;
+    NSUInteger total = view->_totalFrameCount;
+    view = nil;
+    
+    for (int i = 0; i < max; i++, idx++) {
+        @autoreleasepool {
+            if (idx >= total) idx = 0;
+            if ([self isCancelled]) break;
+            __strong YYAnimatedImageView *view = _view;
+            if (!view) break;
+            LOCK_VIEW(BOOL miss = (view->_buffer[@(idx)] == nil));
+            if (miss) {
+                UIImage *img = [_curImage animatedImageFrameAtIndex:idx];
+                img = img.imageByDecoded;
+                if ([self isCancelled]) break;
+                LOCK_VIEW(view->_buffer[@(idx)] = img ? img : [NSNull null]);
+                view = nil;
+            }
+        }
+    }
+}
+@end
+
+@implementation YYAnimatedImageView
+
+- (instancetype)init {
+    self = [super init];
+    _runloopMode = NSRunLoopCommonModes;
+    _autoPlayAnimatedImage = YES;
+    return self;
+}
+
+- (instancetype)initWithFrame:(CGRect)frame {
+    self = [super initWithFrame:frame];
+    _runloopMode = NSRunLoopCommonModes;
+    _autoPlayAnimatedImage = YES;
+    return self;
+}
+
+- (instancetype)initWithImage:(UIImage *)image {
+    self = [super init];
+    _runloopMode = NSRunLoopCommonModes;
+    _autoPlayAnimatedImage = YES;
+    self.frame = (CGRect) {CGPointZero, image.size };
+    self.image = image;
+    return self;
+}
+
+- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage {
+    self = [super init];
+    _runloopMode = NSRunLoopCommonModes;
+    _autoPlayAnimatedImage = YES;
+    CGSize size = image ? image.size : highlightedImage.size;
+    self.frame = (CGRect) {CGPointZero, size };
+    self.image = image;
+    self.highlightedImage = highlightedImage;
+    return self;
+}
+
+// init the animated params.
+- (void)resetAnimated {
+    dispatch_once(&_onceToken, ^{
+        _lock = dispatch_semaphore_create(1);
+        _buffer = [NSMutableDictionary new];
+        _requestQueue = [[NSOperationQueue alloc] init];
+        _requestQueue.maxConcurrentOperationCount = 1;
+        _link = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(step:)];
+        if (_runloopMode) {
+            [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:_runloopMode];
+        }
+        _link.paused = YES;
+        
+        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
+        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
+    });
+    
+    [_requestQueue cancelAllOperations];
+    LOCK(
+         if (_buffer.count) {
+             NSMutableDictionary *holder = _buffer;
+             _buffer = [NSMutableDictionary new];
+             dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
+                 // Capture the dictionary to global queue,
+                 // release these images in background to avoid blocking UI thread.
+                 [holder class];
+             });
+         }
+    );
+    _link.paused = YES;
+    _time = 0;
+    if (_curIndex != 0) {
+        [self willChangeValueForKey:@"currentAnimatedImageIndex"];
+        _curIndex = 0;
+        [self didChangeValueForKey:@"currentAnimatedImageIndex"];
+    }
+    _curAnimatedImage = nil;
+    _curFrame = nil;
+    _curLoop = 0;
+    _totalLoop = 0;
+    _totalFrameCount = 1;
+    _loopEnd = NO;
+    _bufferMiss = NO;
+    _incrBufferCount = 0;
+}
+
+- (void)setImage:(UIImage *)image {
+    if (self.image == image) return;
+    [self setImage:image withType:YYAnimatedImageTypeImage];
+}
+
+- (void)setHighlightedImage:(UIImage *)highlightedImage {
+    if (self.highlightedImage == highlightedImage) return;
+    [self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage];
+}
+
+- (void)setAnimationImages:(NSArray *)animationImages {
+    if (self.animationImages == animationImages) return;
+    [self setImage:animationImages withType:YYAnimatedImageTypeImages];
+}
+
+- (void)setHighlightedAnimationImages:(NSArray *)highlightedAnimationImages {
+    if (self.highlightedAnimationImages == highlightedAnimationImages) return;
+    [self setImage:highlightedAnimationImages withType:YYAnimatedImageTypeHighlightedImages];
+}
+
+- (void)setHighlighted:(BOOL)highlighted {
+    [super setHighlighted:highlighted];
+    if (_link) [self resetAnimated];
+    [self imageChanged];
+}
+
+- (id)imageForType:(YYAnimatedImageType)type {
+    switch (type) {
+        case YYAnimatedImageTypeNone: return nil;
+        case YYAnimatedImageTypeImage: return self.image;
+        case YYAnimatedImageTypeHighlightedImage: return self.highlightedImage;
+        case YYAnimatedImageTypeImages: return self.animationImages;
+        case YYAnimatedImageTypeHighlightedImages: return self.highlightedAnimationImages;
+    }
+    return nil;
+}
+
+- (YYAnimatedImageType)currentImageType {
+    YYAnimatedImageType curType = YYAnimatedImageTypeNone;
+    if (self.highlighted) {
+        if (self.highlightedAnimationImages.count) curType = YYAnimatedImageTypeHighlightedImages;
+        else if (self.highlightedImage) curType = YYAnimatedImageTypeHighlightedImage;
+    }
+    if (curType == YYAnimatedImageTypeNone) {
+        if (self.animationImages.count) curType = YYAnimatedImageTypeImages;
+        else if (self.image) curType = YYAnimatedImageTypeImage;
+    }
+    return curType;
+}
+
+- (void)setImage:(id)image withType:(YYAnimatedImageType)type {
+    [self stopAnimating];
+    if (_link) [self resetAnimated];
+    _curFrame = nil;
+    switch (type) {
+        case YYAnimatedImageTypeNone: break;
+        case YYAnimatedImageTypeImage: super.image = image; break;
+        case YYAnimatedImageTypeHighlightedImage: super.highlightedImage = image; break;
+        case YYAnimatedImageTypeImages: super.animationImages = image; break;
+        case YYAnimatedImageTypeHighlightedImages: super.highlightedAnimationImages = image; break;
+    }
+    [self imageChanged];
+}
+
+- (void)imageChanged {
+    YYAnimatedImageType newType = [self currentImageType];
+    id newVisibleImage = [self imageForType:newType];
+    NSUInteger newImageFrameCount = 0;
+    BOOL hasContentsRect = NO;
+    if ([newVisibleImage isKindOfClass:[UIImage class]] &&
+        [newVisibleImage conformsToProtocol:@protocol(YYAnimatedImage)]) {
+        newImageFrameCount = ((UIImage<YYAnimatedImage> *) newVisibleImage).animatedImageFrameCount;
+        if (newImageFrameCount > 1) {
+            hasContentsRect = [((UIImage<YYAnimatedImage> *) newVisibleImage) respondsToSelector:@selector(animatedImageContentsRectAtIndex:)];
+        }
+    }
+    if (!hasContentsRect && _curImageHasContentsRect) {
+        if (!CGRectEqualToRect(self.layer.contentsRect, CGRectMake(0, 0, 1, 1)) ) {
+            [CATransaction begin];
+            [CATransaction setDisableActions:YES];
+            self.layer.contentsRect = CGRectMake(0, 0, 1, 1);
+            [CATransaction commit];
+        }
+    }
+    _curImageHasContentsRect = hasContentsRect;
+    if (hasContentsRect) {
+        CGRect rect = [((UIImage<YYAnimatedImage> *) newVisibleImage) animatedImageContentsRectAtIndex:0];
+        [self setContentsRect:rect forImage:newVisibleImage];
+    }
+    
+    if (newImageFrameCount > 1) {
+        [self resetAnimated];
+        _curAnimatedImage = newVisibleImage;
+        _curFrame = newVisibleImage;
+        _totalLoop = _curAnimatedImage.animatedImageLoopCount;
+        _totalFrameCount = _curAnimatedImage.animatedImageFrameCount;
+        [self calcMaxBufferCount];
+    }
+    [self setNeedsDisplay];
+    [self didMoved];
+}
+
+// dynamically adjust buffer size for current memory.
+- (void)calcMaxBufferCount {
+    int64_t bytes = (int64_t)_curAnimatedImage.animatedImageBytesPerFrame;
+    if (bytes == 0) bytes = 1024;
+    
+    int64_t total = [UIDevice currentDevice].memoryTotal;
+    int64_t free = [UIDevice currentDevice].memoryFree;
+    int64_t max = MIN(total * 0.2, free * 0.6);
+    max = MAX(max, BUFFER_SIZE);
+    if (_maxBufferSize) max = max > _maxBufferSize ? _maxBufferSize : max;
+    double maxBufferCount = (double)max / (double)bytes;
+    maxBufferCount = YY_CLAMP(maxBufferCount, 1, 512);
+    _maxBufferCount = maxBufferCount;
+}
+
+- (void)dealloc {
+    [_requestQueue cancelAllOperations];
+    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
+    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
+    [_link invalidate];
+}
+
+- (BOOL)isAnimating {
+    return self.currentIsPlayingAnimation;
+}
+
+- (void)stopAnimating {
+    [super stopAnimating];
+    [_requestQueue cancelAllOperations];
+    _link.paused = YES;
+    self.currentIsPlayingAnimation = NO;
+}
+
+- (void)startAnimating {
+    YYAnimatedImageType type = [self currentImageType];
+    if (type == YYAnimatedImageTypeImages || type == YYAnimatedImageTypeHighlightedImages) {
+        NSArray *images = [self imageForType:type];
+        if (images.count > 0) {
+            [super startAnimating];
+            self.currentIsPlayingAnimation = YES;
+        }
+    } else {
+        if (_curAnimatedImage && _link.paused) {
+            _curLoop = 0;
+            _loopEnd = NO;
+            _link.paused = NO;
+            self.currentIsPlayingAnimation = YES;
+        }
+    }
+}
+
+- (void)didReceiveMemoryWarning:(NSNotification *)notification {
+    [_requestQueue cancelAllOperations];
+    [_requestQueue addOperationWithBlock: ^{
+        _incrBufferCount = -60 - (int)(arc4random() % 120); // about 1~3 seconds to grow back..
+        NSNumber *next = @((_curIndex + 1) % _totalFrameCount);
+        LOCK(
+             NSArray * keys = _buffer.allKeys;
+             for (NSNumber * key in keys) {
+                 if (![key isEqualToNumber:next]) { // keep the next frame for smoothly animation
+                     [_buffer removeObjectForKey:key];
+                 }
+             }
+        )//LOCK
+    }];
+}
+
+- (void)didEnterBackground:(NSNotification *)notification {
+    [_requestQueue cancelAllOperations];
+    NSNumber *next = @((_curIndex + 1) % _totalFrameCount);
+    LOCK(
+         NSArray * keys = _buffer.allKeys;
+         for (NSNumber * key in keys) {
+             if (![key isEqualToNumber:next]) { // keep the next frame for smoothly animation
+                 [_buffer removeObjectForKey:key];
+             }
+         }
+     )//LOCK
+}
+
+- (void)step:(CADisplayLink *)link {
+    UIImage <YYAnimatedImage> *image = _curAnimatedImage;
+    NSMutableDictionary *buffer = _buffer;
+    UIImage *bufferedImage = nil;
+    NSUInteger nextIndex = (_curIndex + 1) % _totalFrameCount;
+    BOOL bufferIsFull = NO;
+    
+    if (!image) return;
+    if (_loopEnd) { // view will keep in last frame
+        [self stopAnimating];
+        return;
+    }
+    
+    NSTimeInterval delay = 0;
+    if (!_bufferMiss) {
+        _time += link.duration;
+        delay = [image animatedImageDurationAtIndex:_curIndex];
+        if (_time < delay) return;
+        _time -= delay;
+        if (nextIndex == 0) {
+            _curLoop++;
+            if (_curLoop >= _totalLoop && _totalLoop != 0) {
+                _loopEnd = YES;
+                [self stopAnimating];
+                [self.layer setNeedsDisplay]; // let system call `displayLayer:` before runloop sleep
+                return; // stop at last frame
+            }
+        }
+        delay = [image animatedImageDurationAtIndex:nextIndex];
+        if (_time > delay) _time = delay; // do not jump over frame
+    }
+    LOCK(
+         bufferedImage = buffer[@(nextIndex)];
+         if (bufferedImage) {
+             if ((int)_incrBufferCount < _totalFrameCount) {
+                 [buffer removeObjectForKey:@(nextIndex)];
+             }
+             [self willChangeValueForKey:@"currentAnimatedImageIndex"];
+             _curIndex = nextIndex;
+             [self didChangeValueForKey:@"currentAnimatedImageIndex"];
+             _curFrame = bufferedImage == (id)[NSNull null] ? nil : bufferedImage;
+             if (_curImageHasContentsRect) {
+                 _curContentsRect = [image animatedImageContentsRectAtIndex:_curIndex];
+                 [self setContentsRect:_curContentsRect forImage:_curFrame];
+             }
+             nextIndex = (_curIndex + 1) % _totalFrameCount;
+             _bufferMiss = NO;
+             if (buffer.count == _totalFrameCount) {
+                 bufferIsFull = YES;
+             }
+         } else {
+             _bufferMiss = YES;
+         }
+    )//LOCK
+    
+    if (!_bufferMiss) {
+        [self.layer setNeedsDisplay]; // let system call `displayLayer:` before runloop sleep
+    }
+    
+    if (!bufferIsFull && _requestQueue.operationCount == 0) { // if some work not finished, wait for next opportunity
+        _YYAnimatedImageViewFetchOperation *operation = [_YYAnimatedImageViewFetchOperation new];
+        operation.view = self;
+        operation.nextIndex = nextIndex;
+        operation.curImage = image;
+        [_requestQueue addOperation:operation];
+    }
+}
+
+- (void)displayLayer:(CALayer *)layer {
+    if (_curFrame) {
+        layer.contents = (__bridge id)_curFrame.CGImage;
+    }
+}
+
+- (void)setContentsRect:(CGRect)rect forImage:(UIImage *)image{
+    CGRect layerRect = CGRectMake(0, 0, 1, 1);
+    if (image) {
+        CGSize imageSize = image.size;
+        if (imageSize.width > 0.01 && imageSize.height > 0.01) {
+            layerRect.origin.x = rect.origin.x / imageSize.width;
+            layerRect.origin.y = rect.origin.y / imageSize.height;
+            layerRect.size.width = rect.size.width / imageSize.width;
+            layerRect.size.height = rect.size.height / imageSize.height;
+            layerRect = CGRectIntersection(layerRect, CGRectMake(0, 0, 1, 1));
+            if (CGRectIsNull(layerRect) || CGRectIsEmpty(layerRect)) {
+                layerRect = CGRectMake(0, 0, 1, 1);
+            }
+        }
+    }
+    [CATransaction begin];
+    [CATransaction setDisableActions:YES];
+    self.layer.contentsRect = layerRect;
+    [CATransaction commit];
+}
+
+- (void)didMoved {
+    if (self.autoPlayAnimatedImage) {
+        if(self.superview && self.window) {
+            [self startAnimating];
+        } else {
+            [self stopAnimating];
+        }
+    }
+}
+
+- (void)didMoveToWindow {
+    [super didMoveToWindow];
+    [self didMoved];
+}
+
+- (void)didMoveToSuperview {
+    [super didMoveToSuperview];
+    [self didMoved];
+}
+
+- (void)setCurrentAnimatedImageIndex:(NSUInteger)currentAnimatedImageIndex {
+    if (!_curAnimatedImage) return;
+    if (currentAnimatedImageIndex >= _curAnimatedImage.animatedImageFrameCount) return;
+    if (_curIndex == currentAnimatedImageIndex) return;
+    
+    dispatch_async_on_main_queue(^{
+        LOCK(
+             [_requestQueue cancelAllOperations];
+             [_buffer removeAllObjects];
+             [self willChangeValueForKey:@"currentAnimatedImageIndex"];
+             _curIndex = currentAnimatedImageIndex;
+             [self didChangeValueForKey:@"currentAnimatedImageIndex"];
+             _curFrame = [_curAnimatedImage animatedImageFrameAtIndex:_curIndex];
+             if (_curImageHasContentsRect) {
+                 _curContentsRect = [_curAnimatedImage animatedImageContentsRectAtIndex:_curIndex];
+             }
+             _time = 0;
+             _loopEnd = NO;
+             _bufferMiss = NO;
+             [self.layer setNeedsDisplay];
+         )//LOCK
+    });
+}
+
+- (NSUInteger)currentAnimatedImageIndex {
+    return _curIndex;
+}
+
+- (void)setRunloopMode:(NSString *)runloopMode {
+    if ([_runloopMode isEqual:runloopMode]) return;
+    if (_link) {
+        if (_runloopMode) {
+            [_link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runloopMode];
+        }
+        if (runloopMode.length) {
+            [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:runloopMode];
+        }
+    }
+    _runloopMode = runloopMode.copy;
+}
+
+#pragma mark - Overrice NSObject(NSKeyValueObservingCustomization)
+
++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
+    if ([key isEqualToString:@"currentAnimatedImageIndex"]) {
+        return NO;
+    }
+    return [super automaticallyNotifiesObserversForKey:key];
+}
+
+#pragma mark - NSCoding
+
+- (instancetype)initWithCoder:(NSCoder *)aDecoder {
+    self = [super initWithCoder:aDecoder];
+    _runloopMode = [aDecoder decodeObjectForKey:@"runloopMode"];
+    if (_runloopMode.length == 0) _runloopMode = NSRunLoopCommonModes;
+    if ([aDecoder containsValueForKey:@"autoPlayAnimatedImage"]) {
+        _autoPlayAnimatedImage = [aDecoder decodeBoolForKey:@"autoPlayAnimatedImage"];
+    } else {
+        _autoPlayAnimatedImage = YES;
+    }
+    
+    UIImage *image = [aDecoder decodeObjectForKey:@"YYAnimatedImage"];
+    UIImage *highlightedImage = [aDecoder decodeObjectForKey:@"YYHighlightedAnimatedImage"];
+    if (image) {
+        self.image = image;
+        [self setImage:image withType:YYAnimatedImageTypeImage];
+    }
+    if (highlightedImage) {
+        self.highlightedImage = highlightedImage;
+        [self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage];
+    }
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder:aCoder];
+    [aCoder encodeObject:_runloopMode forKey:@"runloopMode"];
+    [aCoder encodeBool:_autoPlayAnimatedImage forKey:@"autoPlayAnimatedImage"];
+    
+    BOOL ani, multi;
+    ani = [self.image conformsToProtocol:@protocol(YYAnimatedImage)];
+    multi = (ani && ((UIImage <YYAnimatedImage> *)self.image).animatedImageFrameCount > 1);
+    if (multi) [aCoder encodeObject:self.image forKey:@"YYAnimatedImage"];
+    
+    ani = [self.highlightedImage conformsToProtocol:@protocol(YYAnimatedImage)];
+    multi = (ani && ((UIImage <YYAnimatedImage> *)self.highlightedImage).animatedImageFrameCount > 1);
+    if (multi) [aCoder encodeObject:self.highlightedImage forKey:@"YYHighlightedAnimatedImage"];
+}
+
+@end

+ 107 - 0
YYKit/Image/YYFrameImage.h

@@ -0,0 +1,107 @@
+//
+//  YYFrameImage.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/12/9.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYAnimatedImageView.h>
+#else
+#import "YYAnimatedImageView.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ An image to display frame-based animation.
+ 
+ @discussion It is a fully compatible `UIImage` subclass.
+ It only support system image format such as png and jpeg.
+ The animation can be played by YYAnimatedImageView.
+ 
+ Sample Code:
+     
+     NSArray *paths = @[@"/ani/frame1.png", @"/ani/frame2.png", @"/ani/frame3.png"];
+     NSArray *times = @[@0.1, @0.2, @0.1];
+     YYFrameImage *image = [YYFrameImage alloc] initWithImagePaths:paths frameDurations:times repeats:YES];
+     YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image];
+     [view addSubView:imageView];
+ */
+@interface YYFrameImage : UIImage <YYAnimatedImage>
+
+/**
+ Create a frame animated image from files.
+ 
+ @param paths            An array of NSString objects, contains the full or 
+                         partial path to each image file.
+                         e.g. @[@"/ani/1.png",@"/ani/2.png",@"/ani/3.png"]
+ 
+ @param oneFrameDuration The duration (in seconds) per frame.
+ 
+ @param loopCount        The animation loop count, 0 means infinite.
+ 
+ @return An initialized YYFrameImage object, or nil when an error occurs.
+ */
+- (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths
+                           oneFrameDuration:(NSTimeInterval)oneFrameDuration
+                                  loopCount:(NSUInteger)loopCount;
+
+/**
+ Create a frame animated image from files.
+ 
+ @param paths          An array of NSString objects, contains the full or
+                       partial path to each image file.
+                       e.g. @[@"/ani/frame1.png",@"/ani/frame2.png",@"/ani/frame3.png"]
+ 
+ @param frameDurations An array of NSNumber objects, contains the duration (in seconds) per frame.
+                       e.g. @[@0.1, @0.2, @0.3];
+ 
+ @param loopCount      The animation loop count, 0 means infinite.
+ 
+ @return An initialized YYFrameImage object, or nil when an error occurs.
+ */
+- (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths
+                             frameDurations:(NSArray<NSNumber *> *)frameDurations
+                                  loopCount:(NSUInteger)loopCount;
+
+/**
+ Create a frame animated image from an array of data.
+ 
+ @param dataArray        An array of NSData objects.
+ 
+ @param oneFrameDuration The duration (in seconds) per frame.
+ 
+ @param loopCount        The animation loop count, 0 means infinite.
+ 
+ @return An initialized YYFrameImage object, or nil when an error occurs.
+ */
+- (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray
+                               oneFrameDuration:(NSTimeInterval)oneFrameDuration
+                                      loopCount:(NSUInteger)loopCount;
+
+/**
+ Create a frame animated image from an array of data.
+ 
+ @param dataArray      An array of NSData objects.
+ 
+ @param frameDurations An array of NSNumber objects, contains the duration (in seconds) per frame.
+                       e.g. @[@0.1, @0.2, @0.3];
+ 
+ @param loopCount      The animation loop count, 0 means infinite.
+ 
+ @return An initialized YYFrameImage object, or nil when an error occurs.
+ */
+- (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray
+                                 frameDurations:(NSArray *)frameDurations
+                                      loopCount:(NSUInteger)loopCount;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 120 - 0
YYKit/Image/YYFrameImage.m

@@ -0,0 +1,120 @@
+//
+//  YYFrameImage.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/12/9.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYFrameImage.h"
+#import "NSString+YYAdd.h"
+#import "UIImage+YYAdd.h"
+#import "YYImageCoder.h"
+
+@implementation YYFrameImage {
+    NSUInteger _loopCount;
+    NSUInteger _oneFrameBytes;
+    NSArray *_imagePaths;
+    NSArray *_imageDatas;
+    NSArray *_frameDurations;
+}
+
+- (instancetype)initWithImagePaths:(NSArray *)paths oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount {
+    NSMutableArray *durations = [NSMutableArray new];
+    for (int i = 0, max = (int)paths.count; i < max; i++) {
+        [durations addObject:@(oneFrameDuration)];
+    }
+    return [self initWithImagePaths:paths frameDurations:durations loopCount:loopCount];
+}
+
+- (instancetype)initWithImagePaths:(NSArray *)paths frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount {
+    if (paths.count == 0) return nil;
+    if (paths.count != frameDurations.count) return nil;
+    
+    NSString *firstPath = paths[0];
+    NSData *firstData = [NSData dataWithContentsOfFile:firstPath];
+    CGFloat scale = firstPath.pathScale;
+    UIImage *firstCG = [[[UIImage alloc] initWithData:firstData] imageByDecoded];
+    self = [self initWithCGImage:firstCG.CGImage scale:scale orientation:UIImageOrientationUp];
+    if (!self) return nil;
+    long frameByte = CGImageGetBytesPerRow(firstCG.CGImage) * CGImageGetHeight(firstCG.CGImage);
+    _oneFrameBytes = (NSUInteger)frameByte;
+    _imagePaths = paths.copy;
+    _frameDurations = frameDurations.copy;
+    _loopCount = loopCount;
+    
+    return self;
+}
+
+- (instancetype)initWithImageDataArray:(NSArray *)dataArray oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount {
+    NSMutableArray *durations = [NSMutableArray new];
+    for (int i = 0, max = (int)dataArray.count; i < max; i++) {
+        [durations addObject:@(oneFrameDuration)];
+    }
+    return [self initWithImageDataArray:dataArray frameDurations:durations loopCount:loopCount];
+}
+
+- (instancetype)initWithImageDataArray:(NSArray *)dataArray frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount {
+    if (dataArray.count == 0) return nil;
+    if (dataArray.count != frameDurations.count) return nil;
+    
+    NSData *firstData = dataArray[0];
+    CGFloat scale = [UIScreen mainScreen].scale;
+    UIImage *firstCG = [[[UIImage alloc] initWithData:firstData] imageByDecoded];
+    self = [self initWithCGImage:firstCG.CGImage scale:scale orientation:UIImageOrientationUp];
+    if (!self) return nil;
+    long frameByte = CGImageGetBytesPerRow(firstCG.CGImage) * CGImageGetHeight(firstCG.CGImage);
+    _oneFrameBytes = (NSUInteger)frameByte;
+    _imageDatas = dataArray.copy;
+    _frameDurations = frameDurations.copy;
+    _loopCount = loopCount;
+    
+    return self;
+}
+
+#pragma mark - YYAnimtedImage
+
+- (NSUInteger)animatedImageFrameCount {
+    if (_imagePaths) {
+        return _imagePaths.count;
+    } else if (_imageDatas) {
+        return _imageDatas.count;
+    } else {
+        return 1;
+    }
+}
+
+- (NSUInteger)animatedImageLoopCount {
+    return _loopCount;
+}
+
+- (NSUInteger)animatedImageBytesPerFrame {
+    return _oneFrameBytes;
+}
+
+- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
+    if (_imagePaths) {
+        if (index >= _imagePaths.count) return nil;
+        NSString *path = _imagePaths[index];
+        CGFloat scale = [path pathScale];
+        NSData *data = [NSData dataWithContentsOfFile:path];
+        return [[UIImage imageWithData:data scale:scale] imageByDecoded];
+    } else if (_imageDatas) {
+        if (index >= _imageDatas.count) return nil;
+        NSData *data = _imageDatas[index];
+        return [[UIImage imageWithData:data scale:[UIScreen mainScreen].scale] imageByDecoded];
+    } else {
+        return index == 0 ? self : nil;
+    }
+}
+
+- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
+    if (index >= _frameDurations.count) return 0;
+    NSNumber *num = _frameDurations[index];
+    return [num doubleValue];
+}
+
+@end

+ 80 - 0
YYKit/Image/YYImage.h

@@ -0,0 +1,80 @@
+//
+//  YYImage.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/20.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+#if __has_include(<YYKit/YYKit.h>)
+#import <YYKit/YYAnimatedImageView.h>
+#import <YYKit/YYImageCoder.h>
+#else
+#import "YYAnimatedImageView.h"
+#import "YYImageCoder.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ A YYImage object is a high-level way to display animated image data.
+ 
+ @discussion It is a fully compatible `UIImage` subclass. It extends the UIImage
+ to support animated WebP, APNG and GIF format image data decoding. It also 
+ support NSCoding protocol to archive and unarchive multi-frame image data.
+ 
+ If the image is created from multi-frame image data, and you want to play the 
+ animation, try replace UIImageView with `YYAnimatedImageView`.
+ 
+ Sample Code:
+ 
+     // animation@3x.webp
+     YYImage *image = [YYImage imageNamed:@"animation.webp"];
+     YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image];
+     [view addSubView:imageView];
+    
+ */
+@interface YYImage : UIImage <YYAnimatedImage>
+
++ (nullable YYImage *)imageNamed:(NSString *)name; // no cache!
++ (nullable YYImage *)imageWithContentsOfFile:(NSString *)path;
++ (nullable YYImage *)imageWithData:(NSData *)data;
++ (nullable YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale;
+
+/**
+ If the image is created from data or file, then the value indicates the data type.
+ */
+@property (nonatomic, readonly) YYImageType animatedImageType;
+
+/**
+ If the image is created from animated image data (multi-frame GIF/APNG/WebP),
+ this property stores the original image data.
+ */
+@property (nullable, nonatomic, readonly) NSData *animatedImageData;
+
+/**
+ The total memory usage (in bytes) if all frame images was loaded into memory.
+ The value is 0 if the image is not created from a multi-frame image data.
+ */
+@property (nonatomic, readonly) NSUInteger animatedImageMemorySize;
+
+/**
+ Preload all frame image to memory.
+ 
+ @discussion Set this property to `YES` will block the calling thread to decode 
+ all animation frame image to memory, set to `NO` will release the preloaded frames.
+ If the image is shared by lots of image views (such as emoticon), preload all
+ frames will reduce the CPU cost.
+ 
+ See `animatedImageMemorySize` for memory cost.
+ */
+@property (nonatomic) BOOL preloadAllAnimatedImageFrames;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 183 - 0
YYKit/Image/YYImage.m

@@ -0,0 +1,183 @@
+//
+//  YYImage.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 14/10/20.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYImage.h"
+#import "NSString+YYAdd.h"
+#import "NSBundle+YYAdd.h"
+
+@implementation YYImage {
+    YYImageDecoder *_decoder;
+    NSArray *_preloadedFrames;
+    dispatch_semaphore_t _preloadedLock;
+    NSUInteger _bytesPerFrame;
+}
+
++ (YYImage *)imageNamed:(NSString *)name {
+    if (name.length == 0) return nil;
+    if ([name hasSuffix:@"/"]) return nil;
+    
+    NSString *res = name.stringByDeletingPathExtension;
+    NSString *ext = name.pathExtension;
+    NSString *path = nil;
+    CGFloat scale = 1;
+    
+    // If no extension, guess by system supported (same as UIImage).
+    NSArray *exts = ext.length > 0 ? @[ext] : @[@"", @"png", @"jpeg", @"jpg", @"gif", @"webp", @"apng"];
+    NSArray *scales = [NSBundle preferredScales];
+    for (int s = 0; s < scales.count; s++) {
+        scale = ((NSNumber *)scales[s]).floatValue;
+        NSString *scaledName = [res stringByAppendingNameScale:scale];
+        for (NSString *e in exts) {
+            path = [[NSBundle mainBundle] pathForResource:scaledName ofType:e];
+            if (path) break;
+        }
+        if (path) break;
+    }
+    if (path.length == 0) return nil;
+    
+    NSData *data = [NSData dataWithContentsOfFile:path];
+    if (data.length == 0) return nil;
+    
+    return [[self alloc] initWithData:data scale:scale];
+}
+
++ (YYImage *)imageWithContentsOfFile:(NSString *)path {
+    return [[self alloc] initWithContentsOfFile:path];
+}
+
++ (YYImage *)imageWithData:(NSData *)data {
+    return [[self alloc] initWithData:data];
+}
+
++ (YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale {
+    return [[self alloc] initWithData:data scale:scale];
+}
+
+- (instancetype)initWithContentsOfFile:(NSString *)path {
+    NSData *data = [NSData dataWithContentsOfFile:path];
+    return [self initWithData:data scale:path.pathScale];
+}
+
+- (instancetype)initWithData:(NSData *)data {
+    return [self initWithData:data scale:1];
+}
+
+- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale {
+    if (data.length == 0) return nil;
+    if (scale <= 0) scale = [UIScreen mainScreen].scale;
+    _preloadedLock = dispatch_semaphore_create(1);
+    @autoreleasepool {
+        YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:scale];
+        YYImageFrame *frame = [decoder frameAtIndex:0 decodeForDisplay:YES];
+        UIImage *image = frame.image;
+        if (!image) return nil;
+        self = [self initWithCGImage:image.CGImage scale:decoder.scale orientation:image.imageOrientation];
+        if (!self) return nil;
+        _animatedImageType = decoder.type;
+        if (decoder.frameCount > 1) {
+            _decoder = decoder;
+            _bytesPerFrame = CGImageGetBytesPerRow(image.CGImage) * CGImageGetHeight(image.CGImage);
+            _animatedImageMemorySize = _bytesPerFrame * decoder.frameCount;
+        }
+        self.isDecodedForDisplay = YES;
+    }
+    return self;
+}
+
+- (NSData *)animatedImageData {
+    return _decoder.data;
+}
+
+- (void)setPreloadAllAnimatedImageFrames:(BOOL)preloadAllAnimatedImageFrames {
+    if (_preloadAllAnimatedImageFrames != preloadAllAnimatedImageFrames) {
+        if (preloadAllAnimatedImageFrames && _decoder.frameCount > 0) {
+            NSMutableArray *frames = [NSMutableArray new];
+            for (NSUInteger i = 0, max = _decoder.frameCount; i < max; i++) {
+                UIImage *img = [self animatedImageFrameAtIndex:i];
+                if (img) {
+                    [frames addObject:img];
+                } else {
+                    [frames addObject:[NSNull null]];
+                }
+            }
+            dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER);
+            _preloadedFrames = frames;
+            dispatch_semaphore_signal(_preloadedLock);
+        } else {
+            dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER);
+            _preloadedFrames = nil;
+            dispatch_semaphore_signal(_preloadedLock);
+        }
+    }
+}
+
+#pragma mark - protocol NSCoding
+
+- (instancetype)initWithCoder:(NSCoder *)aDecoder {
+    NSNumber *scale = [aDecoder decodeObjectForKey:@"YYImageScale"];
+    NSData *data = [aDecoder decodeObjectForKey:@"YYImageData"];
+    if (data.length) {
+        self = [self initWithData:data scale:scale.doubleValue];
+    } else {
+        self = [super initWithCoder:aDecoder];
+    }
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    if (_decoder.data.length) {
+        [aCoder encodeObject:@(self.scale) forKey:@"YYImageScale"];
+        [aCoder encodeObject:_decoder.data forKey:@"YYImageData"];
+    } else {
+        [super encodeWithCoder:aCoder]; // Apple use UIImagePNGRepresentation() to encode UIImage.
+    }
+}
+
+#pragma mark - protocol YYAnimatedImage
+
+- (NSUInteger)animatedImageFrameCount {
+    return _decoder.frameCount;
+}
+
+- (NSUInteger)animatedImageLoopCount {
+    return _decoder.loopCount;
+}
+
+- (NSUInteger)animatedImageBytesPerFrame {
+    return _bytesPerFrame;
+}
+
+- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
+    if (index >= _decoder.frameCount) return nil;
+    dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER);
+    UIImage *image = _preloadedFrames[index];
+    dispatch_semaphore_signal(_preloadedLock);
+    if (image) return image == (id)[NSNull null] ? nil : image;
+    return [_decoder frameAtIndex:index decodeForDisplay:YES].image;
+}
+
+- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
+    NSTimeInterval duration = [_decoder frameDurationAtIndex:index];
+    
+    /*
+     http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
+     Many annoying ads specify a 0 duration to make an image flash as quickly as 
+     possible. We follow Safari and Firefox's behavior and use a duration of 100 ms 
+     for any frames that specify a duration of <= 10 ms.
+     See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
+     
+     See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
+     */
+    if (duration < 0.011f) return 0.100f;
+    return duration;
+}
+
+@end

+ 228 - 0
YYKit/Image/YYImageCache.h

@@ -0,0 +1,228 @@
+//
+//  YYImageCache.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+@class YYMemoryCache, YYDiskCache;
+
+NS_ASSUME_NONNULL_BEGIN
+
+/// Image cache type
+typedef NS_OPTIONS(NSUInteger, YYImageCacheType) {
+    /// No value.
+    YYImageCacheTypeNone   = 0,
+    
+    /// Get/store image with memory cache.
+    YYImageCacheTypeMemory = 1 << 0,
+    
+    /// Get/store image with disk cache.
+    YYImageCacheTypeDisk   = 1 << 1,
+    
+    /// Get/store image with both memory cache and disk cache.
+    YYImageCacheTypeAll    = YYImageCacheTypeMemory | YYImageCacheTypeDisk,
+};
+
+
+/**
+ YYImageCache is a cache that stores UIImage and image data based on memory cache and disk cache.
+ 
+ @discussion The disk cache will try to protect the original image data:
+ 
+ * If the original image is still image, it will be saved as png/jpeg file based on alpha information.
+ * If the original image is animated gif, apng or webp, it will be saved as original format.
+ * If the original image's scale is not 1, the scale value will be saved as extended data.
+ 
+ Although UIImage can be serialized with NSCoding protocol, but it's not a good idea:
+ Apple actually use UIImagePNGRepresentation() to encode all kind of image, it may 
+ lose the original multi-frame data. The result is packed to plist file and cannot
+ view with photo viewer directly. If the image has no alpha channel, using JPEG 
+ instead of PNG can save more disk size and encoding/decoding time.
+ */
+@interface YYImageCache : NSObject
+
+#pragma mark - Attribute
+///=============================================================================
+/// @name Attribute
+///=============================================================================
+
+/** The name of the cache. Default is nil. */
+@property (nullable, copy) NSString *name;
+
+/** The underlying memory cache. see `YYMemoryCache` for more information.*/
+@property (strong, readonly) YYMemoryCache *memoryCache;
+
+/** The underlying disk cache. see `YYDiskCache` for more information.*/
+@property (strong, readonly) YYDiskCache *diskCache;
+
+/**
+ Whether decode animated image when fetch image from disk cache. Default is YES.
+ 
+ @discussion When fetch image from disk cache, it will use 'YYImage' to decode 
+ animated image such as WebP/APNG/GIF. Set to 'NO' to ignore animated image.
+ */
+@property BOOL allowAnimatedImage;
+
+/**
+ Whether decode the image to memory bitmap. Default is YES.
+ 
+ @discussion If the value is YES, then the image will be decoded to memory bitmap
+ for better display performance, but may cost more memory.
+ */
+@property BOOL decodeForDisplay;
+
+
+#pragma mark - Initializer
+///=============================================================================
+/// @name Initializer
+///=============================================================================
+- (instancetype)init UNAVAILABLE_ATTRIBUTE;
++ (instancetype)new UNAVAILABLE_ATTRIBUTE;
+
+/**
+ Returns global shared image cache instance.
+ @return  The singleton YYImageCache instance.
+ */
++ (instancetype)sharedCache;
+
+/**
+ The designated initializer. Multiple instances with the same path will make the
+ cache unstable.
+ 
+ @param path Full path of a directory in which the cache will write data.
+ Once initialized you should not read and write to this directory.
+ @result A new cache object, or nil if an error occurs.
+ */
+- (nullable instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER;
+
+
+#pragma mark - Access Methods
+///=============================================================================
+/// @name Access Methods
+///=============================================================================
+
+/**
+ Sets the image with the specified key in the cache (both memory and disk).
+ This method returns immediately and executes the store operation in background.
+ 
+ @param image The image to be stored in the cache. If nil, this method has no effect.
+ @param key   The key with which to associate the image. If nil, this method has no effect.
+ */
+- (void)setImage:(UIImage *)image forKey:(NSString *)key;
+
+/**
+ Sets the image with the specified key in the cache.
+ This method returns immediately and executes the store operation in background.
+ 
+ @discussion If the `type` contain `YYImageCacheTypeMemory`, then the `image` will 
+ be stored in the memory cache; `imageData` will be used instead if `image` is nil.
+ If the `type` contain `YYImageCacheTypeDisk`, then the `imageData` will
+ be stored in the disk cache; `image` will be used instead if `imageData` is nil.
+ 
+ @param image     The image to be stored in the cache.
+ @param imageData The image data to be stored in the cache.
+ @param key       The key with which to associate the image. If nil, this method has no effect.
+ @param type      The cache type to store image.
+ */
+- (void)setImage:(nullable UIImage *)image
+       imageData:(nullable NSData *)imageData
+          forKey:(NSString *)key
+        withType:(YYImageCacheType)type;
+
+/**
+ Removes the image of the specified key in the cache (both memory and disk).
+ This method returns immediately and executes the remove operation in background.
+ 
+ @param key The key identifying the image to be removed. If nil, this method has no effect.
+ */
+- (void)removeImageForKey:(NSString *)key;
+
+/**
+ Removes the image of the specified key in the cache.
+ This method returns immediately and executes the remove operation in background.
+ 
+ @param key  The key identifying the image to be removed. If nil, this method has no effect.
+ @param type The cache type to remove image.
+ */
+- (void)removeImageForKey:(NSString *)key withType:(YYImageCacheType)type;
+
+/**
+ Returns a Boolean value that indicates whether a given key is in cache.
+ If the image is not in memory, this method may blocks the calling thread until 
+ file read finished.
+ 
+ @param key A string identifying the image. If nil, just return NO.
+ @return Whether the image is in cache.
+ */
+- (BOOL)containsImageForKey:(NSString *)key;
+
+/**
+ Returns a Boolean value that indicates whether a given key is in cache.
+ If the image is not in memory and the `type` contains `YYImageCacheTypeDisk`,
+ this method may blocks the calling thread until file read finished.
+ 
+ @param key  A string identifying the image. If nil, just return NO.
+ @param type The cache type.
+ @return Whether the image is in cache.
+ */
+- (BOOL)containsImageForKey:(NSString *)key withType:(YYImageCacheType)type;
+
+/**
+ Returns the image associated with a given key.
+ If the image is not in memory, this method may blocks the calling thread until
+ file read finished.
+ 
+ @param key A string identifying the image. If nil, just return nil.
+ @return The image associated with key, or nil if no image is associated with key.
+ */
+- (nullable UIImage *)getImageForKey:(NSString *)key;
+
+/**
+ Returns the image associated with a given key.
+ If the image is not in memory and the `type` contains `YYImageCacheTypeDisk`,
+ this method may blocks the calling thread until file read finished.
+ 
+ @param key A string identifying the image. If nil, just return nil.
+ @return The image associated with key, or nil if no image is associated with key.
+ */
+- (nullable UIImage *)getImageForKey:(NSString *)key withType:(YYImageCacheType)type;
+
+/**
+ Asynchronously get the image associated with a given key.
+ 
+ @param key   A string identifying the image. If nil, just return nil.
+ @param type  The cache type.
+ @param block A completion block which will be called on main thread.
+ */
+- (void)getImageForKey:(NSString *)key
+              withType:(YYImageCacheType)type
+             withBlock:(void(^)(UIImage * _Nullable image, YYImageCacheType type))block;
+
+/**
+ Returns the image data associated with a given key.
+ This method may blocks the calling thread until file read finished.
+ 
+ @param key A string identifying the image. If nil, just return nil.
+ @return The image data associated with key, or nil if no image is associated with key.
+ */
+- (nullable NSData *)getImageDataForKey:(NSString *)key;
+
+/**
+ Asynchronously get the image data associated with a given key.
+ 
+ @param key   A string identifying the image. If nil, just return nil.
+ @param block A completion block which will be called on main thread.
+ */
+- (void)getImageDataForKey:(NSString *)key
+                 withBlock:(void(^)(NSData * _Nullable imageData))block;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 255 - 0
YYKit/Image/YYImageCache.m

@@ -0,0 +1,255 @@
+//
+//  YYImageCache.m
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/2/15.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import "YYImageCache.h"
+#import "YYMemoryCache.h"
+#import "YYDiskCache.h"
+#import "UIImage+YYAdd.h"
+#import "NSObject+YYAdd.h"
+#import "YYImage.h"
+
+#if __has_include("YYDispatchQueuePool.h")
+#import "YYDispatchQueuePool.h"
+#endif
+
+
+static inline dispatch_queue_t YYImageCacheIOQueue() {
+#ifdef YYDispatchQueuePool_h
+    return YYDispatchQueueGetForQOS(NSQualityOfServiceDefault);
+#else
+    return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+#endif
+}
+
+static inline dispatch_queue_t YYImageCacheDecodeQueue() {
+#ifdef YYDispatchQueuePool_h
+    return YYDispatchQueueGetForQOS(NSQualityOfServiceUtility);
+#else
+    return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
+#endif
+}
+
+
+@interface YYImageCache ()
+- (NSUInteger)imageCost:(UIImage *)image;
+- (UIImage *)imageFromData:(NSData *)data;
+@end
+
+
+@implementation YYImageCache
+
+- (NSUInteger)imageCost:(UIImage *)image {
+    CGImageRef cgImage = image.CGImage;
+    if (!cgImage) return 1;
+    CGFloat height = CGImageGetHeight(cgImage);
+    size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
+    NSUInteger cost = bytesPerRow * height;
+    if (cost == 0) cost = 1;
+    return cost;
+}
+
+- (UIImage *)imageFromData:(NSData *)data {
+    NSData *scaleData = [YYDiskCache getExtendedDataFromObject:data];
+    CGFloat scale = 0;
+    if (scaleData) {
+        scale = ((NSNumber *)[NSKeyedUnarchiver unarchiveObjectWithData:scaleData]).doubleValue;
+    }
+    if (scale <= 0) scale = [UIScreen mainScreen].scale;
+    UIImage *image;
+    if (_allowAnimatedImage) {
+        image = [[YYImage alloc] initWithData:data scale:scale];
+        if (_decodeForDisplay) image = [image imageByDecoded];
+    } else {
+        YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:scale];
+        image = [decoder frameAtIndex:0 decodeForDisplay:_decodeForDisplay].image;
+    }
+    return image;
+}
+
+#pragma mark Public
+
++ (instancetype)sharedCache {
+    static YYImageCache *cache = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
+                                                                   NSUserDomainMask, YES) firstObject];
+        cachePath = [cachePath stringByAppendingPathComponent:@"com.ibireme.yykit"];
+        cachePath = [cachePath stringByAppendingPathComponent:@"images"];
+        cache = [[self alloc] initWithPath:cachePath];
+    });
+    return cache;
+}
+
+- (instancetype)init {
+    @throw [NSException exceptionWithName:@"YYImageCache init error" reason:@"YYImageCache must be initialized with a path. Use 'initWithPath:' instead." userInfo:nil];
+    return [self initWithPath:@""];
+}
+
+- (instancetype)initWithPath:(NSString *)path {
+    YYMemoryCache *memoryCache = [YYMemoryCache new];
+    memoryCache.shouldRemoveAllObjectsOnMemoryWarning = YES;
+    memoryCache.shouldRemoveAllObjectsWhenEnteringBackground = YES;
+    memoryCache.countLimit = NSUIntegerMax;
+    memoryCache.costLimit = NSUIntegerMax;
+    memoryCache.ageLimit = 12 * 60 * 60;
+    
+    YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:path];
+    diskCache.customArchiveBlock = ^(id object) { return (NSData *)object; };
+    diskCache.customUnarchiveBlock = ^(NSData *data) { return (id)data; };
+    if (!memoryCache || !diskCache) return nil;
+    
+    self = [super init];
+    _memoryCache = memoryCache;
+    _diskCache = diskCache;
+    _allowAnimatedImage = YES;
+    _decodeForDisplay = YES;
+    return self;
+}
+
+- (void)setImage:(UIImage *)image forKey:(NSString *)key {
+    [self setImage:image imageData:nil forKey:key withType:YYImageCacheTypeAll];
+}
+
+- (void)setImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key withType:(YYImageCacheType)type {
+    if (!key || (image == nil && imageData.length == 0)) return;
+    
+    __weak typeof(self) _self = self;
+    if (type & YYImageCacheTypeMemory) { // add to memory cache
+        if (image) {
+            if (image.isDecodedForDisplay) {
+                [_memoryCache setObject:image forKey:key withCost:[_self imageCost:image]];
+            } else {
+                dispatch_async(YYImageCacheDecodeQueue(), ^{
+                    __strong typeof(_self) self = _self;
+                    if (!self) return;
+                    [self.memoryCache setObject:[image imageByDecoded] forKey:key withCost:[self imageCost:image]];
+                });
+            }
+        } else if (imageData) {
+            dispatch_async(YYImageCacheDecodeQueue(), ^{
+                __strong typeof(_self) self = _self;
+                if (!self) return;
+                UIImage *newImage = [self imageFromData:imageData];
+                [self.memoryCache setObject:newImage forKey:key withCost:[self imageCost:newImage]];
+            });
+        }
+    }
+    if (type & YYImageCacheTypeDisk) { // add to disk cache
+        if (imageData) {
+            if (image) {
+                [YYDiskCache setExtendedData:[NSKeyedArchiver archivedDataWithRootObject:@(image.scale)] toObject:imageData];
+            }
+            [_diskCache setObject:imageData forKey:key];
+        } else if (image) {
+            dispatch_async(YYImageCacheIOQueue(), ^{
+                __strong typeof(_self) self = _self;
+                if (!self) return;
+                NSData *data = [image imageDataRepresentation];
+                [YYDiskCache setExtendedData:[NSKeyedArchiver archivedDataWithRootObject:@(image.scale)] toObject:data];
+                [self.diskCache setObject:data forKey:key];
+            });
+        }
+    }
+}
+
+- (void)removeImageForKey:(NSString *)key {
+    [self removeImageForKey:key withType:YYImageCacheTypeAll];
+}
+
+- (void)removeImageForKey:(NSString *)key withType:(YYImageCacheType)type {
+    if (type & YYImageCacheTypeMemory) [_memoryCache removeObjectForKey:key];
+    if (type & YYImageCacheTypeDisk) [_diskCache removeObjectForKey:key];
+}
+
+- (BOOL)containsImageForKey:(NSString *)key {
+    return [self containsImageForKey:key withType:YYImageCacheTypeAll];
+}
+
+- (BOOL)containsImageForKey:(NSString *)key withType:(YYImageCacheType)type {
+    if (type & YYImageCacheTypeMemory) {
+        if ([_memoryCache containsObjectForKey:key]) return YES;
+    }
+    if (type & YYImageCacheTypeDisk) {
+        if ([_diskCache containsObjectForKey:key]) return YES;
+    }
+    return NO;
+}
+
+- (UIImage *)getImageForKey:(NSString *)key {
+    return [self getImageForKey:key withType:YYImageCacheTypeAll];
+}
+
+- (UIImage *)getImageForKey:(NSString *)key withType:(YYImageCacheType)type {
+    if (!key) return nil;
+    if (type & YYImageCacheTypeMemory) {
+        UIImage *image = [_memoryCache objectForKey:key];
+        if (image) return image;
+    }
+    if (type & YYImageCacheTypeDisk) {
+        NSData *data = (id)[_diskCache objectForKey:key];
+        UIImage *image = [self imageFromData:data];
+        if (image && (type & YYImageCacheTypeMemory)) {
+            [_memoryCache setObject:image forKey:key withCost:[self imageCost:image]];
+        }
+        return image;
+    }
+    return nil;
+}
+
+- (void)getImageForKey:(NSString *)key withType:(YYImageCacheType)type withBlock:(void (^)(UIImage *image, YYImageCacheType type))block {
+    if (!block) return;
+    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+        UIImage *image = nil;
+        
+        if (type & YYImageCacheTypeMemory) {
+            image = [_memoryCache objectForKey:key];
+            if (image) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    block(image, YYImageCacheTypeMemory);
+                });
+                return;
+            }
+        }
+        
+        if (type & YYImageCacheTypeDisk) {
+            NSData *data = (id)[_diskCache objectForKey:key];
+            image = [self imageFromData:data];
+            if (image) {
+                [_memoryCache setObject:image forKey:key];
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    block(image, YYImageCacheTypeDisk);
+                });
+                return;
+            }
+        }
+        
+        dispatch_async(dispatch_get_main_queue(), ^{
+            block(nil, YYImageCacheTypeNone);
+        });
+    });
+}
+
+- (NSData *)getImageDataForKey:(NSString *)key {
+    return (id)[_diskCache objectForKey:key];
+}
+
+- (void)getImageDataForKey:(NSString *)key withBlock:(void (^)(NSData *imageData))block {
+    if (!block) return;
+    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+        NSData *data = (id)[_diskCache objectForKey:key];
+        dispatch_async(dispatch_get_main_queue(), ^{
+            block(data);
+        });
+    });
+}
+
+@end

+ 505 - 0
YYKit/Image/YYImageCoder.h

@@ -0,0 +1,505 @@
+//
+//  YYImageCoder.h
+//  YYKit <https://github.com/ibireme/YYKit>
+//
+//  Created by ibireme on 15/5/13.
+//  Copyright (c) 2015 ibireme.
+//
+//  This source code is licensed under the MIT-style license found in the
+//  LICENSE file in the root directory of this source tree.
+//
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Image file type.
+ */
+typedef NS_ENUM(NSUInteger, YYImageType) {
+    YYImageTypeUnknown = 0, ///< unknown
+    YYImageTypeJPEG,        ///< jpeg, jpg
+    YYImageTypeJPEG2000,    ///< jp2
+    YYImageTypeTIFF,        ///< tiff, tif
+    YYImageTypeBMP,         ///< bmp
+    YYImageTypeICO,         ///< ico
+    YYImageTypeICNS,        ///< icns
+    YYImageTypeGIF,         ///< gif
+    YYImageTypePNG,         ///< png
+    YYImageTypeWebP,        ///< webp
+    YYImageTypeOther,       ///< other image format
+};
+
+
+/**
+ Dispose method specifies how the area used by the current frame is to be treated
+ before rendering the next frame on the canvas.
+ */
+typedef NS_ENUM(NSUInteger, YYImageDisposeMethod) {
+    
+    /**
+     No disposal is done on this frame before rendering the next; the contents
+     of the canvas are left as is.
+     */
+    YYImageDisposeNone = 0,
+    
+    /**
+     The frame's region of the canvas is to be cleared to fully transparent black
+     before rendering the next frame.
+     */
+    YYImageDisposeBackground,
+    
+    /**
+     The frame's region of the canvas is to be reverted to the previous contents
+     before rendering the next frame.
+     */
+    YYImageDisposePrevious,
+};
+
+/**
+ Blend operation specifies how transparent pixels of the current frame are
+ blended with those of the previous canvas.
+ */
+typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
+    
+    /**
+     All color components of the frame, including alpha, overwrite the current
+     contents of the frame's canvas region.
+     */
+    YYImageBlendNone = 0,
+    
+    /**
+     The frame should be composited onto the output buffer based on its alpha.
+     */
+    YYImageBlendOver,
+};
+
+/**
+ An image frame object.
+ */
+@interface YYImageFrame : NSObject <NSCopying>
+@property (nonatomic) NSUInteger index;    ///< Frame index (zero based)
+@property (nonatomic) NSUInteger width;    ///< Frame width
+@property (nonatomic) NSUInteger height;   ///< Frame height
+@property (nonatomic) NSUInteger offsetX;  ///< Frame origin.x in canvas (left-bottom based)
+@property (nonatomic) NSUInteger offsetY;  ///< Frame origin.y in canvas (left-bottom based)
+@property (nonatomic) NSTimeInterval duration;          ///< Frame duration in seconds
+@property (nonatomic) YYImageDisposeMethod dispose;     ///< Frame dispose method.
+@property (nonatomic) YYImageBlendOperation blend;      ///< Frame blend operation.
+@property (nullable, nonatomic, strong) UIImage *image; ///< The image.
++ (instancetype)frameWithImage:(UIImage *)image;
+@end
+
+
+#pragma mark - Decoder
+
+/**
+ An image decoder to decode image data.
+ 
+ @discussion This class supports decoding animated WebP, APNG, GIF and system
+ image format such as PNG, JPG, JP2, BMP, TIFF, PIC, ICNS and ICO. It can be used 
+ to decode complete image data, or to decode incremental image data during image 
+ download. This class is thread-safe.
+ 
+ Example:
+ 
+    // Decode single image:
+    NSData *data = [NSData dataWithContentOfFile:@"/tmp/image.webp"];
+    YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:2.0];
+    UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
+ 
+    // Decode image during download:
+    NSMutableData *data = [NSMutableData new];
+    YYImageDecoder *decoder = [[YYImageDecoder alloc] initWithScale:2.0];
+    while(newDataArrived) {
+        [data appendData:newData];
+        [decoder updateData:data final:NO];
+        if (decoder.frameCount > 0) {
+            UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
+            // progressive display...
+        }
+    }
+    [decoder updateData:data final:YES];
+    UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
+    // final display...
+ 
+ */
+@interface YYImageDecoder : NSObject
+
+@property (nullable, nonatomic, readonly) NSData *data;    ///< Image data.
+@property (nonatomic, readonly) YYImageType type;          ///< Image data type.
+@property (nonatomic, readonly) CGFloat scale;             ///< Image scale.
+@property (nonatomic, readonly) NSUInteger frameCount;     ///< Image frame count.
+@property (nonatomic, readonly) NSUInteger loopCount;      ///< Image loop count, 0 means infinite.
+@property (nonatomic, readonly) NSUInteger width;          ///< Image canvas width.
+@property (nonatomic, readonly) NSUInteger height;         ///< Image canvas height.
+@property (nonatomic, readonly, getter=isFinalized) BOOL finalized;
+
+/**
+ Creates an image decoder.
+ 
+ @param scale  Image's scale.
+ @return An image decoder.
+ */
+- (instancetype)initWithScale:(CGFloat)scale NS_DESIGNATED_INITIALIZER;
+
+/**
+ Updates the incremental image with new data.
+ 
+ @discussion You can use this method to decode progressive/interlaced/baseline
+ image when you do not have the complete image data. The `data` was retained by
+ decoder, you should not modify the data in other thread during decoding.
+ 
+ @param data  The data to add to the image decoder. Each time you call this 
+ function, the 'data' parameter must contain all of the image file data 
+ accumulated so far.
+ 
+ @param final  A value that specifies whether the data is the final set. 
+ Pass YES if it is, NO otherwise. When the data is already finalized, you can
+ not update the data anymore.
+ 
+ @return Whether succeed.
+ */
+- (BOOL)updateData:(nullable NSData *)data final:(BOOL)final;
+
+/**
+ Convenience method to create a decoder with specified data.
+ @param data  Image data.
+ @param scale Image's scale.
+ @return A new decoder, or nil if an error occurs.
+ */
++ (nullable instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale;
+
+/**
+ Decodes and returns a frame from a specified index.
+ @param index  Frame image index (zero-based).
+ @param decodeForDisplay Whether decode the image to memory bitmap for display.
+    If NO, it will try to returns the original frame data without blend.
+ @return A new frame with image, or nil if an error occurs.
+ */
+- (nullable YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay;
+
+/**
+ Returns the frame duration from a specified index.
+ @param index  Frame image (zero-based).
+ @return Duration in seconds.
+ */
+- (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index;
+
+/**
+ Returns the frame's properties. See "CGImageProperties.h" in ImageIO.framework
+ for more information.
+ 
+ @param index  Frame image index (zero-based).
+ @return The ImageIO frame property.
+ */
+- (nullable NSDictionary *)framePropertiesAtIndex:(NSUInteger)index;
+
+/**
+ Returns the image's properties. See "CGImageProperties.h" in ImageIO.framework
+ for more information.
+ */
+- (nullable NSDictionary *)imageProperties;
+
+@end
+
+
+
+#pragma mark - Encoder
+
+/**
+ An image encoder to encode image to data.
+ 
+ @discussion It supports encoding single frame image with the type defined in YYImageType.
+ It also supports encoding multi-frame image with GIF, APNG and WebP.
+ 
+ Example:
+    
+    YYImageEncoder *jpegEncoder = [[YYImageEncoder alloc] initWithType:YYImageTypeJPEG];
+    jpegEncoder.quality = 0.9;
+    [jpegEncoder addImage:image duration:0];
+    NSData jpegData = [jpegEncoder encode];
+ 
+    YYImageEncoder *gifEncoder = [[YYImageEncoder alloc] initWithType:YYImageTypeGIF];
+    gifEncoder.loopCount = 5;
+    [gifEncoder addImage:image0 duration:0.1];
+    [gifEncoder addImage:image1 duration:0.15];
+    [gifEncoder addImage:image2 duration:0.2];
+    NSData gifData = [gifEncoder encode];
+ 
+ @warning It just pack the images together when encoding multi-frame image. If you
+ want to reduce the image file size, try imagemagick/ffmpeg for GIF and WebP,
+ and apngasm for APNG.
+ */
+@interface YYImageEncoder : NSObject
+
+@property (nonatomic, readonly) YYImageType type; ///< Image type.
+@property (nonatomic) NSUInteger loopCount;       ///< Loop count, 0 means infinit, only available for GIF/APNG/WebP.
+@property (nonatomic) BOOL lossless;              ///< Lossless, only available for WebP.
+@property (nonatomic) CGFloat quality;            ///< Compress quality, 0.0~1.0, only available for JPG/JP2/WebP.
+
+- (instancetype)init UNAVAILABLE_ATTRIBUTE;
++ (instancetype)new UNAVAILABLE_ATTRIBUTE;
+
+/**
+ Create an image encoder with a specified type.
+ @param type Image type.
+ @return A new encoder, or nil if an error occurs.
+ */
+- (nullable instancetype)initWithType:(YYImageType)type NS_DESIGNATED_INITIALIZER;
+
+/**
+ Add an image to encoder.
+ @param image    Image.
+ @param duration Image duration for animation. Pass 0 to ignore this parameter.
+ */
+- (void)addImage:(UIImage *)image duration:(NSTimeInterval)duration;
+
+/**
+ Add an image with image data to encoder.
+ @param data    Image data.
+ @param duration Image duration for animation. Pass 0 to ignore this parameter.
+ */
+- (void)addImageWithData:(NSData *)data duration:(NSTimeInterval)duration;
+
+/**
+ Add an image from a file path to encoder.
+ @param image    Image file path.
+ @param duration Image duration for animation. Pass 0 to ignore this parameter.
+ */
+- (void)addImageWithFile:(NSString *)path duration:(NSTimeInterval)duration;
+
+/**
+ Encodes the image and returns the image data.
+ @return The image data, or nil if an error occurs.
+ */
+- (nullable NSData *)encode;
+
+/**
+ Encodes the image to a file.
+ @param path The file path (overwrite if exist).
+ @return Whether succeed.
+ */
+- (BOOL)encodeToFile:(NSString *)path;
+
+/**
+ Convenience method to encode single frame image.
+ @param image   The image.
+ @param type    The destination image type.
+ @param quality Image quality, 0.0~1.0.
+ @return The image data, or nil if an error occurs.
+ */
++ (nullable NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality;
+
+/**
+ Convenience method to encode image from a decoder.
+ @param decoder The image decoder.
+ @param type    The destination image type;
+ @param quality Image quality, 0.0~1.0.
+ @return The image data, or nil if an error occurs.
+ */
++ (nullable NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality;
+
+@end
+
+
+#pragma mark - UIImage
+
+@interface UIImage (YYImageCoder)
+
+/**
+ Decompress this image to bitmap, so when the image is displayed on screen, 
+ the main thread won't be blocked by additional decode. If the image has already
+ been decoded or unable to decode, it just returns itself.
+ 
+ @return an image decoded, or just return itself if no needed.
+ @see isDecodedForDisplay
+ */
+- (instancetype)imageByDecoded;
+
+/**
+ Wherher the image can be display on screen without additional decoding.
+ @warning It just a hint for your code, change it has no other effect.
+ */
+@property (nonatomic) BOOL isDecodedForDisplay;
+
+/**
+ Saves this image to iOS Photos Album. 
+ 
+ @discussion  This method attempts to save the original data to album if the
+ image is created from an animated GIF/APNG, otherwise, it will save the image 
+ as JPEG or PNG (based on the alpha information).
+ 
+ @param completionBlock The block invoked (in main thread) after the save operation completes.
+    assetURL: An URL that identifies the saved image file. If the image is not saved, assetURL is nil.
+    error: If the image is not saved, an error object that describes the reason for failure, otherwise nil.
+ */
+- (void)saveToAlbumWithCompletionBlock:(nullable void(^)(NSURL * _Nullable assetURL, NSError * _Nullable error))completionBlock;
+
+/**
+ Return a 'best' data representation for this image.
+ 
+ @discussion The convertion based on these rule:
+ 1. If the image is created from an animated GIF/APNG/WebP, it returns the original data.
+ 2. It returns PNG or JPEG(0.9) representation based on the alpha information.
+ 
+ @return Image data, or nil if an error occurs.
+ */
+- (nullable NSData *)imageDataRepresentation;
+
+@end
+
+
+
+#pragma mark - Helper
+
+/// Detect a data's image type by reading the data's header 16 bytes (very fast).
+CG_EXTERN YYImageType YYImageDetectType(CFDataRef data);
+
+/// Convert YYImageType to UTI (such as kUTTypeJPEG).
+CG_EXTERN CFStringRef _Nullable YYImageTypeToUTType(YYImageType type);
+
+/// Convert UTI (such as kUTTypeJPEG) to YYImageType.
+CG_EXTERN YYImageType YYImageTypeFromUTType(CFStringRef uti);
+
+/// Get image type's file extension (such as @"jpg").
+CG_EXTERN NSString *_Nullable YYImageTypeGetExtension(YYImageType type);
+
+
+
+/// Returns the shared DeviceRGB color space.
+CG_EXTERN CGColorSpaceRef YYCGColorSpaceGetDeviceRGB();
+
+/// Returns the shared DeviceGray color space.
+CG_EXTERN CGColorSpaceRef YYCGColorSpaceGetDeviceGray();
+
+/// Returns whether a color space is DeviceRGB.
+CG_EXTERN BOOL YYCGColorSpaceIsDeviceRGB(CGColorSpaceRef space);
+
+/// Returns whether a color space is DeviceGray.
+CG_EXTERN BOOL YYCGColorSpaceIsDeviceGray(CGColorSpaceRef space);
+
+
+
+/// Convert EXIF orientation value to UIImageOrientation.
+CG_EXTERN UIImageOrientation YYUIImageOrientationFromEXIFValue(NSInteger value);
+
+/// Convert UIImageOrientation to EXIF orientation value.
+CG_EXTERN NSInteger YYUIImageOrientationToEXIFValue(UIImageOrientation orientation);
+
+
+
+/**
+ Create a decoded image.
+ 
+ @discussion If the source image is created from a compressed image data (such as
+ PNG or JPEG), you can use this method to decode the image. After decoded, you can
+ access the decoded bytes with CGImageGetDataProvider() and CGDataProviderCopyData()
+ without additional decode process. If the image has already decoded, this method
+ just copy the decoded bytes to the new image.
+ 
+ @param imageRef          The source image.
+ @param decodeForDisplay  If YES, this method will decode the image and convert
+          it to BGRA8888 (premultiplied) or BGRX8888 format for CALayer display.
+ 
+ @return A decoded image, or NULL if an error occurs.
+ */
+CG_EXTERN CGImageRef _Nullable YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay);
+
+/**
+ Create an image copy with an orientation.
+ 
+ @param imageRef       Source image
+ @param orientation    Image orientation which will applied to the image.
+ @param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
+ @return A new image, or NULL if an error occurs.
+ */
+CG_EXTERN CGImageRef _Nullable YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
+                                                                  UIImageOrientation orientation,
+                                                                  CGBitmapInfo destBitmapInfo);
+
+/**
+ Create an image copy with CGAffineTransform.
+ 
+ @param imageRef       Source image.
+ @param transform      Transform applied to image (left-bottom based coordinate system).
+ @param destSize       Destination image size
+ @param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
+ @return A new image, or NULL if an error occurs.
+ */
+CG_EXTERN CGImageRef _Nullable YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
+                                                                  CGAffineTransform transform,
+                                                                  CGSize destSize,
+                                                                  CGBitmapInfo destBitmapInfo);
+
+/**
+ Encode an image to data with CGImageDestination.
+ 
+ @param imageRef  The image.
+ @param type      The image destination data type.
+ @param quality   The quality (0.0~1.0)
+ @return A new image data, or nil if an error occurs.
+ */
+CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality);
+
+
+/**
+ Whether WebP is available in YYImage.
+ */
+CG_EXTERN BOOL YYImageWebPAvailable();
+
+/**
+ Get a webp image frame count;
+ 
+ @param webpData WebP data.
+ @return Image frame count, or 0 if an error occurs.
+ */
+CG_EXTERN NSUInteger YYImageGetWebPFrameCount(CFDataRef webpData);
+
+/**
+ Decode an image from WebP data, returns NULL if an error occurs.
+ 
+ @param webpData          The WebP data.
+ @param decodeForDisplay  If YES, this method will decode the image and convert it
+                            to BGRA8888 (premultiplied) format for CALayer display.
+ @param useThreads        YES to enable multi-thread decode.
+                            (speed up, but cost more CPU)
+ @param bypassFiltering   YES to skip the in-loop filtering.
+                            (speed up, but may lose some smooth)
+ @param noFancyUpsampling YES to use faster pointwise upsampler.
+                            (speed down, and may lose some details).
+ @return The decoded image, or NULL if an error occurs.
+ */
+CG_EXTERN CGImageRef _Nullable YYCGImageCreateWithWebPData(CFDataRef webpData,
+                                                           BOOL decodeForDisplay,
+                                                           BOOL useThreads,
+                                                           BOOL bypassFiltering,
+                                                           BOOL noFancyUpsampling);
+
+typedef NS_ENUM(NSUInteger, YYImagePreset) {
+    YYImagePresetDefault = 0,  ///< default preset.
+    YYImagePresetPicture,      ///< digital picture, like portrait, inner shot
+    YYImagePresetPhoto,        ///< outdoor photograph, with natural lighting
+    YYImagePresetDrawing,      ///< hand or line drawing, with high-contrast details
+    YYImagePresetIcon,         ///< small-sized colorful images
+    YYImagePresetText          ///< text-like
+};
+
+/**
+ Encode a CGImage to WebP data
+ 
+ @param imageRef      image
+ @param lossless      YES=lossless (similar to PNG), NO=lossy (similar to JPEG)
+ @param quality       0.0~1.0 (0=smallest file, 1.0=biggest file)
+                      For lossless image, try the value near 1.0; for lossy, try the value near 0.8.
+ @param compressLevel 0~6 (0=fast, 6=slower-better). Default is 4.
+ @param preset        Preset for different image type, default is YYImagePresetDefault.
+ @return WebP data, or nil if an error occurs.
+ */
+CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedWebPData(CGImageRef imageRef,
+                                                             BOOL lossless,
+                                                             CGFloat quality,
+                                                             int compressLevel,
+                                                             YYImagePreset preset);
+
+NS_ASSUME_NONNULL_END

Some files were not shown because too many files changed in this diff