You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

619 lines
16 KiB

  1. YYModel
  2. ==============
  3. [![License MIT](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/ibireme/YYModel/master/LICENSE) 
  4. [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) 
  5. [![CocoaPods](http://img.shields.io/cocoapods/v/YYModel.svg?style=flat)](http://cocoapods.org/?q= YYModel) 
  6. [![CocoaPods](http://img.shields.io/cocoapods/p/YYModel.svg?style=flat)](http://cocoapods.org/?q= YYModel) 
  7. [![Build Status](https://travis-ci.org/ibireme/YYModel.svg?branch=master)](https://travis-ci.org/ibireme/YYModel) 
  8. [![codecov.io](https://codecov.io/github/ibireme/YYModel/coverage.svg?branch=master)](https://codecov.io/github/ibireme/YYModel?branch=master)
  9. High performance model framework for iOS/OSX.<br/>
  10. (It's a component of [YYKit](https://github.com/ibireme/YYKit))
  11. Performance
  12. ==============
  13. Time cost (process GithubUser 10000 times on iPhone 6):
  14. ![Benchmark result](https://raw.github.com/ibireme/YYModel/master/Benchmark/Result.png
  15. )
  16. See `Benchmark/ModelBenchmark.xcodeproj` for more benchmark case.
  17. Features
  18. ==============
  19. - **High performance**: The conversion performance is close to handwriting code.
  20. - **Automatic type conversion**: The object types can be automatically converted.
  21. - **Type Safe**: All data types will be verified to ensure type-safe during the conversion process.
  22. - **Non-intrusive**: There is no need to make the model class inherit from other base class.
  23. - **Lightwight**: This library contains only 5 files.
  24. - **Docs and unit testing**: 100% docs coverage, 99.6% code coverage.
  25. Usage
  26. ==============
  27. ###Simple model json convert
  28. // JSON:
  29. {
  30. "uid":123456,
  31. "name":"Harry",
  32. "created":"1965-07-31T00:00:00+0000"
  33. }
  34. // Model:
  35. @interface User : NSObject
  36. @property UInt64 uid;
  37. @property NSString *name;
  38. @property NSDate *created;
  39. @end
  40. @implementation User
  41. @end
  42. // Convert json to model:
  43. User *user = [User yy_modelWithJSON:json];
  44. // Convert model to json:
  45. NSDictionary *json = [user yy_modelToJSONObject];
  46. If the type of an object in JSON/Dictionary cannot be matched to the property of the model, the following automatic conversion is performed. If the automatic conversion failed, the value will be ignored.
  47. <table>
  48. <thead>
  49. <tr>
  50. <th>JSON/Dictionary</th>
  51. <th>Model</th>
  52. </tr>
  53. </thead>
  54. <tbody>
  55. <tr>
  56. <td>NSString</td>
  57. <td>NSNumber,NSURL,SEL,Class</td>
  58. </tr>
  59. <tr>
  60. <td>NSNumber</td>
  61. <td>NSString</td>
  62. </tr>
  63. <tr>
  64. <td>NSString/NSNumber</td>
  65. <td>C number (BOOL,int,float,NSUInteger,UInt64,...)<br/>
  66. NaN and Inf will be ignored</td>
  67. </tr>
  68. <tr>
  69. <td>NSString</td>
  70. <td>NSDate parsed with these formats:<br/>
  71. yyyy-MM-dd<br/>
  72. yyyy-MM-dd HH:mm:ss<br/>
  73. yyyy-MM-dd'T'HH:mm:ss<br/>
  74. yyyy-MM-dd'T'HH:mm:ssZ<br/>
  75. EEE MMM dd HH:mm:ss Z yyyy
  76. </td>
  77. </tr>
  78. <tr>
  79. <td>NSDate</td>
  80. <td>NSString formatted with ISO8601:<br/>
  81. "YYYY-MM-dd'T'HH:mm:ssZ"</td>
  82. </tr>
  83. <tr>
  84. <td>NSValue</td>
  85. <td>struct (CGRect,CGSize,...)</td>
  86. </tr>
  87. <tr>
  88. <td>NSNull</td>
  89. <td>nil,0</td>
  90. </tr>
  91. <tr>
  92. <td>"no","false",...</td>
  93. <td>@(NO),0</td>
  94. </tr>
  95. <tr>
  96. <td>"yes","true",...</td>
  97. <td>@(YES),1</td>
  98. </tr>
  99. </tbody>
  100. </table>
  101. ###Match model property to different JSON key
  102. // JSON:
  103. {
  104. "n":"Harry Pottery",
  105. "p": 256,
  106. "ext" : {
  107. "desc" : "A book written by J.K.Rowing."
  108. },
  109. "ID" : 100010
  110. }
  111. // Model:
  112. @interface Book : NSObject
  113. @property NSString *name;
  114. @property NSInteger page;
  115. @property NSString *desc;
  116. @property NSString *bookID;
  117. @end
  118. @implementation Book
  119. + (NSDictionary *)modelCustomPropertyMapper {
  120. return @{@"name" : @"n",
  121. @"page" : @"p",
  122. @"desc" : @"ext.desc",
  123. @"bookID" : @[@"id",@"ID",@"book_id"]};
  124. }
  125. @end
  126. You can map a json key (key path) or an array of json key (key path) to one or multiple property name. If there's no mapper for a property, it will use the property's name as default.
  127. ###Nested model
  128. // JSON
  129. {
  130. "author":{
  131. "name":"J.K.Rowling",
  132. "birthday":"1965-07-31T00:00:00+0000"
  133. },
  134. "name":"Harry Potter",
  135. "pages":256
  136. }
  137. // Model: (no need to do anything)
  138. @interface Author : NSObject
  139. @property NSString *name;
  140. @property NSDate *birthday;
  141. @end
  142. @implementation Author
  143. @end
  144. @interface Book : NSObject
  145. @property NSString *name;
  146. @property NSUInteger pages;
  147. @property Author *author;
  148. @end
  149. @implementation Book
  150. @end
  151. ### Container property
  152. @class Shadow, Border, Attachment;
  153. @interface Attributes
  154. @property NSString *name;
  155. @property NSArray *shadows; //Array<Shadow>
  156. @property NSSet *borders; //Set<Border>
  157. @property NSMutableDictionary *attachments; //Dict<NSString,Attachment>
  158. @end
  159. @implementation Attributes
  160. + (NSDictionary *)modelContainerPropertyGenericClass {
  161. // value should be Class or Class name.
  162. return @{@"shadows" : [Shadow class],
  163. @"borders" : Border.class,
  164. @"attachments" : @"Attachment" };
  165. }
  166. @end
  167. ### Whitelist and blacklist
  168. @interface User
  169. @property NSString *name;
  170. @property NSUInteger age;
  171. @end
  172. @implementation Attributes
  173. + (NSArray *)modelPropertyBlacklist {
  174. return @[@"test1", @"test2"];
  175. }
  176. + (NSArray *)modelPropertyWhitelist {
  177. return @[@"name"];
  178. }
  179. @end
  180. ###Data validate and custom transform
  181. // JSON:
  182. {
  183. "name":"Harry",
  184. "timestamp" : 1445534567
  185. }
  186. // Model:
  187. @interface User
  188. @property NSString *name;
  189. @property NSDate *createdAt;
  190. @end
  191. @implementation User
  192. - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
  193. NSNumber *timestamp = dic[@"timestamp"];
  194. if (![timestamp isKindOfClass:[NSNumber class]]) return NO;
  195. _createdAt = [NSDate dateWithTimeIntervalSince1970:timestamp.floatValue];
  196. return YES;
  197. }
  198. - (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
  199. if (!_createdAt) return NO;
  200. dic[@"timestamp"] = @(n.timeIntervalSince1970);
  201. return YES;
  202. }
  203. @end
  204. ###Coding/Copying/hash/equal/description
  205. @interface YYShadow :NSObject <NSCoding, NSCopying>
  206. @property (nonatomic, copy) NSString *name;
  207. @property (nonatomic, assign) CGSize size;
  208. @end
  209. @implementation YYShadow
  210. - (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
  211. - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
  212. - (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; }
  213. - (NSUInteger)hash { return [self yy_modelHash]; }
  214. - (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; }
  215. - (NSString *)description { return [self yy_modelDescription]; }
  216. @end
  217. Installation
  218. ==============
  219. ### CocoaPods
  220. 1. Add `pod 'YYModel'` to your Podfile.
  221. 2. Run `pod install` or `pod update`.
  222. 3. Import \<YYModel/YYModel.h\>.
  223. ### Carthage
  224. 1. Add `github "ibireme/YYModel"` to your Cartfile.
  225. 2. Run `carthage update --platform ios` and add the framework to your project.
  226. 3. Import \<YYModel/YYModel.h\>.
  227. ### Manually
  228. 1. Download all the files in the YYModel subdirectory.
  229. 2. Add the source files to your Xcode project.
  230. 3. Import `YYModel.h`.
  231. Documentation
  232. ==============
  233. Full API documentation is available on [CocoaDocs](http://cocoadocs.org/docsets/YYModel/).<br/>
  234. You can also install documentation locally using [appledoc](https://github.com/tomaz/appledoc).
  235. Requirements
  236. ==============
  237. This library requires `iOS 6.0+` and `Xcode 7.0+`.
  238. License
  239. ==============
  240. YYModel is provided under the MIT license. See LICENSE file for details.
  241. <br/><br/>
  242. ---
  243. 中文介绍
  244. ==============
  245. 高性能 iOS/OSX 模型转换框架。<br/>
  246. (该项目是 [YYKit](https://github.com/ibireme/YYKit) 组件之一)
  247. 性能
  248. ==============
  249. 处理 GithubUser 数据 10000 次耗时统计 (iPhone 6):
  250. ![Benchmark result](https://raw.github.com/ibireme/YYModel/master/Benchmark/Result.png
  251. )
  252. 更多测试代码和用例见 `Benchmark/ModelBenchmark.xcodeproj`
  253. 特性
  254. ==============
  255. - **高性能**: 模型转换性能接近手写解析代码。
  256. - **自动类型转换**: 对象类型可以自动转换,详情见下方表格。
  257. - **类型安全**: 转换过程中,所有的数据类型都会被检测一遍,以保证类型安全,避免崩溃问题。
  258. - **无侵入性**: 模型无需继承自其他基类。
  259. - **轻量**: 该框架只有 5 个文件 (包括.h文件)。
  260. - **文档和单元测试**: 文档覆盖率100%, 代码覆盖率99.6%。
  261. 使用方法
  262. ==============
  263. ###简单的 Model 与 JSON 相互转换
  264. // JSON:
  265. {
  266. "uid":123456,
  267. "name":"Harry",
  268. "created":"1965-07-31T00:00:00+0000"
  269. }
  270. // Model:
  271. @interface User : NSObject
  272. @property UInt64 uid;
  273. @property NSString *name;
  274. @property NSDate *created;
  275. @end
  276. @implementation User
  277. @end
  278. // 将 JSON (NSData,NSString,NSDictionary) 转换为 Model:
  279. User *user = [User yy_modelWithJSON:json];
  280. // 将 Model 转换为 JSON 对象:
  281. NSDictionary *json = [user yy_modelToJSONObject];
  282. 当 JSON/Dictionary 中的对象类型与 Model 属性不一致时,YYModel 将会进行如下自动转换。自动转换不支持的值将会被忽略,以避免各种潜在的崩溃问题。
  283. <table>
  284. <thead>
  285. <tr>
  286. <th>JSON/Dictionary</th>
  287. <th>Model</th>
  288. </tr>
  289. </thead>
  290. <tbody>
  291. <tr>
  292. <td>NSString</td>
  293. <td>NSNumber,NSURL,SEL,Class</td>
  294. </tr>
  295. <tr>
  296. <td>NSNumber</td>
  297. <td>NSString</td>
  298. </tr>
  299. <tr>
  300. <td>NSString/NSNumber</td>
  301. <td>基础类型 (BOOL,int,float,NSUInteger,UInt64,...)<br/>
  302. NaN 和 Inf 会被忽略</td>
  303. </tr>
  304. <tr>
  305. <td>NSString</td>
  306. <td>NSDate 以下列格式解析:<br/>
  307. yyyy-MM-dd<br/>
  308. yyyy-MM-dd HH:mm:ss<br/>
  309. yyyy-MM-dd'T'HH:mm:ss<br/>
  310. yyyy-MM-dd'T'HH:mm:ssZ<br/>
  311. EEE MMM dd HH:mm:ss Z yyyy
  312. </td>
  313. </tr>
  314. <tr>
  315. <td>NSDate</td>
  316. <td>NSString 格式化为 ISO8601:<br/>
  317. "YYYY-MM-dd'T'HH:mm:ssZ"</td>
  318. </tr>
  319. <tr>
  320. <td>NSValue</td>
  321. <td>struct (CGRect,CGSize,...)</td>
  322. </tr>
  323. <tr>
  324. <td>NSNull</td>
  325. <td>nil,0</td>
  326. </tr>
  327. <tr>
  328. <td>"no","false",...</td>
  329. <td>@(NO),0</td>
  330. </tr>
  331. <tr>
  332. <td>"yes","true",...</td>
  333. <td>@(YES),1</td>
  334. </tr>
  335. </tbody>
  336. </table>
  337. ###Model 属性名和 JSON 中的 Key 不相同
  338. // JSON:
  339. {
  340. "n":"Harry Pottery",
  341. "p": 256,
  342. "ext" : {
  343. "desc" : "A book written by J.K.Rowing."
  344. },
  345. "ID" : 100010
  346. }
  347. // Model:
  348. @interface Book : NSObject
  349. @property NSString *name;
  350. @property NSInteger page;
  351. @property NSString *desc;
  352. @property NSString *bookID;
  353. @end
  354. @implementation Book
  355. //返回一个 Dict,将 Model 属性名对映射到 JSON 的 Key。
  356. + (NSDictionary *)modelCustomPropertyMapper {
  357. return @{@"name" : @"n",
  358. @"page" : @"p",
  359. @"desc" : @"ext.desc",
  360. @"bookID" : @[@"id",@"ID",@"book_id"]};
  361. }
  362. @end
  363. 你可以把一个或一组 json key (key path) 映射到一个或多个属性。如果一个属性没有映射关系,那默认会使用相同属性名作为映射。
  364. 在 json->model 的过程中:如果一个属性对应了多个 json key,那么转换过程会按顺序查找,并使用第一个不为空的值。
  365. 在 model->json 的过程中:如果一个属性对应了多个 json key (key path),那么转换过程仅会处理第一个 json key (key path);如果多个属性对应了同一个 json key,则转换过过程会使用其中任意一个不为空的值。
  366. ###Model 包含其他 Model
  367. // JSON
  368. {
  369. "author":{
  370. "name":"J.K.Rowling",
  371. "birthday":"1965-07-31T00:00:00+0000"
  372. },
  373. "name":"Harry Potter",
  374. "pages":256
  375. }
  376. // Model: 什么都不用做,转换会自动完成
  377. @interface Author : NSObject
  378. @property NSString *name;
  379. @property NSDate *birthday;
  380. @end
  381. @implementation Author
  382. @end
  383. @interface Book : NSObject
  384. @property NSString *name;
  385. @property NSUInteger pages;
  386. @property Author *author; //Book 包含 Author 属性
  387. @end
  388. @implementation Book
  389. @end
  390. ###容器类属性
  391. @class Shadow, Border, Attachment;
  392. @interface Attributes
  393. @property NSString *name;
  394. @property NSArray *shadows; //Array<Shadow>
  395. @property NSSet *borders; //Set<Border>
  396. @property NSMutableDictionary *attachments; //Dict<NSString,Attachment>
  397. @end
  398. @implementation Attributes
  399. // 返回容器类中的所需要存放的数据类型 (以 Class 或 Class Name 的形式)。
  400. + (NSDictionary *)modelContainerPropertyGenericClass {
  401. return @{@"shadows" : [Shadow class],
  402. @"borders" : Border.class,
  403. @"attachments" : @"Attachment" };
  404. }
  405. @end
  406. ###黑名单与白名单
  407. @interface User
  408. @property NSString *name;
  409. @property NSUInteger age;
  410. @end
  411. @implementation Attributes
  412. // 如果实现了该方法,则处理过程中会忽略该列表内的所有属性
  413. + (NSArray *)modelPropertyBlacklist {
  414. return @[@"test1", @"test2"];
  415. }
  416. // 如果实现了该方法,则处理过程中不会处理该列表外的属性。
  417. + (NSArray *)modelPropertyWhitelist {
  418. return @[@"name"];
  419. }
  420. @end
  421. ###数据校验与自定义转换
  422. // JSON:
  423. {
  424. "name":"Harry",
  425. "timestamp" : 1445534567
  426. }
  427. // Model:
  428. @interface User
  429. @property NSString *name;
  430. @property NSDate *createdAt;
  431. @end
  432. @implementation User
  433. // 当 JSON 转为 Model 完成后,该方法会被调用。
  434. // 你可以在这里对数据进行校验,如果校验不通过,可以返回 NO,则该 Model 会被忽略。
  435. // 你也可以在这里做一些自动转换不能完成的工作。
  436. - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
  437. NSNumber *timestamp = dic[@"timestamp"];
  438. if (![timestamp isKindOfClass:[NSNumber class]]) return NO;
  439. _createdAt = [NSDate dateWithTimeIntervalSince1970:timestamp.floatValue];
  440. return YES;
  441. }
  442. // 当 Model 转为 JSON 完成后,该方法会被调用。
  443. // 你可以在这里对数据进行校验,如果校验不通过,可以返回 NO,则该 Model 会被忽略。
  444. // 你也可以在这里做一些自动转换不能完成的工作。
  445. - (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
  446. if (!_createdAt) return NO;
  447. dic[@"timestamp"] = @(n.timeIntervalSince1970);
  448. return YES;
  449. }
  450. @end
  451. ###Coding/Copying/hash/equal/description
  452. @interface YYShadow :NSObject <NSCoding, NSCopying>
  453. @property (nonatomic, copy) NSString *name;
  454. @property (nonatomic, assign) CGSize size;
  455. @end
  456. @implementation YYShadow
  457. // 直接添加以下代码即可自动完成
  458. - (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
  459. - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
  460. - (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; }
  461. - (NSUInteger)hash { return [self yy_modelHash]; }
  462. - (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; }
  463. - (NSString *)description { return [self yy_modelDescription]; }
  464. @end
  465. 安装
  466. ==============
  467. ### CocoaPods
  468. 1. 在 Podfile 中添加 `pod 'YYModel'`
  469. 2. 执行 `pod install``pod update`
  470. 3. 导入 \<YYModel/YYModel.h\>。
  471. ### Carthage
  472. 1. 在 Cartfile 中添加 `github "ibireme/YYModel"`
  473. 2. 执行 `carthage update --platform ios` 并将生成的 framework 添加到你的工程。
  474. 3. 导入 \<YYModel/YYModel.h\>。
  475. ### 手动安装
  476. 1. 下载 YYModel 文件夹内的所有内容。
  477. 2. 将 YYModel 内的源文件添加(拖放)到你的工程。
  478. 3. 导入 `YYModel.h`
  479. 文档
  480. ==============
  481. 你可以在 [CocoaDocs](http://cocoadocs.org/docsets/YYModel/) 查看在线 API 文档,也可以用 [appledoc](https://github.com/tomaz/appledoc) 本地生成文档。
  482. 系统要求
  483. ==============
  484. 该项目最低支持 `iOS 6.0``Xcode 7.0`
  485. 许可证
  486. ==============
  487. YYModel 使用 MIT 许可证,详情见 LICENSE 文件。
  488. 相关链接
  489. ==============
  490. [iOS JSON 模型转换库评测](http://blog.ibireme.com/2015/10/23/ios_model_framework_benchmark/)