NSObject+YYModel.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //
  2. // NSObject+YYModel.h
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 15/5/10.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import <Foundation/Foundation.h>
  12. NS_ASSUME_NONNULL_BEGIN
  13. /**
  14. Provide some data-model method:
  15. * Convert json to any object, or convert any object to json.
  16. * Set object properties with a key-value dictionary (like KVC).
  17. * Implementations of `NSCoding`, `NSCopying`, `-hash` and `-isEqual:`.
  18. See `YYModel` protocol for custom methods.
  19. Sample Code:
  20. ********************** json convertor *********************
  21. @code
  22. @interface YYAuthor : NSObject
  23. @property (nonatomic, strong) NSString *name;
  24. @property (nonatomic, assign) NSDate *birthday;
  25. @end
  26. @implementation YYAuthor
  27. @end
  28. @interface YYBook : NSObject
  29. @property (nonatomic, copy) NSString *name;
  30. @property (nonatomic, assign) NSUInteger pages;
  31. @property (nonatomic, strong) YYAuthor *author;
  32. @end
  33. @implementation YYBook
  34. @end
  35. int main() {
  36. // create model from json
  37. YYBook *book = [YYBook modelWithJSON:@"{\"name\": \"Harry Potter\", \"pages\": 256, \"author\": {\"name\": \"J.K.Rowling\", \"birthday\": \"1965-07-31\" }}"];
  38. // convert model to json
  39. NSString *json = [book modelToJSONString];
  40. // {"author":{"name":"J.K.Rowling","birthday":"1965-07-31T00:00:00+0000"},"name":"Harry Potter","pages":256}
  41. }
  42. @endcode
  43. ********************** Coding/Copying/hash/equal *********************
  44. @code
  45. @interface YYShadow :NSObject <NSCoding, NSCopying>
  46. @property (nonatomic, copy) NSString *name;
  47. @property (nonatomic, assign) CGSize size;
  48. @end
  49. @implementation YYShadow
  50. - (void)encodeWithCoder:(NSCoder *)aCoder { [self modelEncodeWithCoder:aCoder]; }
  51. - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self modelInitWithCoder:aDecoder]; }
  52. - (id)copyWithZone:(NSZone *)zone { return [self modelCopy]; }
  53. - (NSUInteger)hash { return [self modelHash]; }
  54. - (BOOL)isEqual:(id)object { return [self modelIsEqual:object]; }
  55. @end
  56. @endcode
  57. */
  58. @interface NSObject (YYModel)
  59. /**
  60. Creates and returns a new instance of the receiver from a json.
  61. This method is thread-safe.
  62. @param json A json object in `NSDictionary`, `NSString` or `NSData`.
  63. @return A new instance created from the json, or nil if an error occurs.
  64. */
  65. + (nullable instancetype)modelWithJSON:(id)json;
  66. /**
  67. Creates and returns a new instance of the receiver from a key-value dictionary.
  68. This method is thread-safe.
  69. @param dictionary A key-value dictionary mapped to the instance's properties.
  70. Any invalid key-value pair in dictionary will be ignored.
  71. @return A new instance created from the dictionary, or nil if an error occurs.
  72. @discussion The key in `dictionary` will mapped to the reciever's property name,
  73. and the value will set to the property. If the value's type does not match the
  74. property, this method will try to convert the value based on these rules:
  75. `NSString` or `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger...
  76. `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd".
  77. `NSString` -> NSURL.
  78. `NSValue` -> struct or union, such as CGRect, CGSize, ...
  79. `NSString` -> SEL, Class.
  80. */
  81. + (nullable instancetype)modelWithDictionary:(NSDictionary *)dictionary;
  82. /**
  83. Set the receiver's properties with a json object.
  84. @discussion Any invalid data in json will be ignored.
  85. @param json A json object of `NSDictionary`, `NSString` or `NSData`, mapped to the
  86. receiver's properties.
  87. @return Whether succeed.
  88. */
  89. - (BOOL)modelSetWithJSON:(id)json;
  90. /**
  91. Set the receiver's properties with a key-value dictionary.
  92. @param dic A key-value dictionary mapped to the receiver's properties.
  93. Any invalid key-value pair in dictionary will be ignored.
  94. @discussion The key in `dictionary` will mapped to the reciever's property name,
  95. and the value will set to the property. If the value's type doesn't match the
  96. property, this method will try to convert the value based on these rules:
  97. `NSString`, `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger...
  98. `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd".
  99. `NSString` -> NSURL.
  100. `NSValue` -> struct or union, such as CGRect, CGSize, ...
  101. `NSString` -> SEL, Class.
  102. @return Whether succeed.
  103. */
  104. - (BOOL)modelSetWithDictionary:(NSDictionary *)dic;
  105. /**
  106. Generate a json object from the receiver's properties.
  107. @return A json object in `NSDictionary` or `NSArray`, or nil if an error occurs.
  108. See [NSJSONSerialization isValidJSONObject] for more information.
  109. @discussion Any of the invalid property is ignored.
  110. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it just convert
  111. the inner object to json object.
  112. */
  113. - (nullable id)modelToJSONObject;
  114. /**
  115. Generate a json string's data from the receiver's properties.
  116. @return A json string's data, or nil if an error occurs.
  117. @discussion Any of the invalid property is ignored.
  118. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the
  119. inner object to json string.
  120. */
  121. - (nullable NSData *)modelToJSONData;
  122. /**
  123. Generate a json string from the receiver's properties.
  124. @return A json string, or nil if an error occurs.
  125. @discussion Any of the invalid property is ignored.
  126. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the
  127. inner object to json string.
  128. */
  129. - (nullable NSString *)modelToJSONString;
  130. /**
  131. Copy a instance with the receiver's properties.
  132. @return A copied instance, or nil if an error occurs.
  133. */
  134. - (nullable id)modelCopy;
  135. /**
  136. Encode the receiver's properties to a coder.
  137. @param aCoder An archiver object.
  138. */
  139. - (void)modelEncodeWithCoder:(NSCoder *)aCoder;
  140. /**
  141. Decode the receiver's properties from a decoder.
  142. @param aDecoder An archiver object.
  143. @return self
  144. */
  145. - (id)modelInitWithCoder:(NSCoder *)aDecoder;
  146. /**
  147. Get a hash code with the receiver's properties.
  148. @return Hash code.
  149. */
  150. - (NSUInteger)modelHash;
  151. /**
  152. Compares the receiver with another object for equality, based on properties.
  153. @param model Another object.
  154. @return `YES` if the reciever is equal to the object, otherwise `NO`.
  155. */
  156. - (BOOL)modelIsEqual:(id)model;
  157. /**
  158. Description method for debugging purposes based on properties.
  159. @return A string that describes the contents of the receiver.
  160. */
  161. - (NSString *)modelDescription;
  162. @end
  163. /**
  164. Provide some data-model method for NSArray.
  165. */
  166. @interface NSArray (YYModel)
  167. /**
  168. Creates and returns an array from a json-array.
  169. This method is thread-safe.
  170. @param cls The instance's class in array.
  171. @param json A json array of `NSArray`, `NSString` or `NSData`.
  172. Example: [{"name":"Mary"},{name:"Joe"}]
  173. @return A array, or nil if an error occurs.
  174. */
  175. + (nullable NSArray *)modelArrayWithClass:(Class)cls json:(id)json;
  176. @end
  177. /**
  178. Provide some data-model method for NSDictionary.
  179. */
  180. @interface NSDictionary (YYModel)
  181. /**
  182. Creates and returns a dictionary from a json.
  183. This method is thread-safe.
  184. @param cls The value instance's class in dictionary.
  185. @param json A json dictionary of `NSDictionary`, `NSString` or `NSData`.
  186. Example: {"user1":{"name","Mary"}, "user2": {name:"Joe"}}
  187. @return A dictionary, or nil if an error occurs.
  188. */
  189. + (nullable NSDictionary *)modelDictionaryWithClass:(Class)cls json:(id)json;
  190. @end
  191. /**
  192. If the default model transform does not fit to your model class, implement one or
  193. more method in this protocol to change the default key-value transform process.
  194. There's no need to add '<YYModel>' to your class header.
  195. */
  196. @protocol YYModel <NSObject>
  197. @optional
  198. /**
  199. Custom property mapper.
  200. @discussion If the key in JSON/Dictionary does not match to the model's property name,
  201. implements this method and returns the additional mapper.
  202. Example:
  203. json:
  204. {
  205. "n":"Harry Pottery",
  206. "p": 256,
  207. "ext" : {
  208. "desc" : "A book written by J.K.Rowling."
  209. },
  210. "ID" : 100010
  211. }
  212. model:
  213. @code
  214. @interface YYBook : NSObject
  215. @property NSString *name;
  216. @property NSInteger page;
  217. @property NSString *desc;
  218. @property NSString *bookID;
  219. @end
  220. @implementation YYBook
  221. + (NSDictionary *)modelCustomPropertyMapper {
  222. return @{@"name" : @"n",
  223. @"page" : @"p",
  224. @"desc" : @"ext.desc",
  225. @"bookID": @[@"id", @"ID", @"book_id"]};
  226. }
  227. @end
  228. @endcode
  229. @return A custom mapper for properties.
  230. */
  231. + (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper;
  232. /**
  233. The generic class mapper for container properties.
  234. @discussion If the property is a container object, such as NSArray/NSSet/NSDictionary,
  235. implements this method and returns a property->class mapper, tells which kind of
  236. object will be add to the array/set/dictionary.
  237. Example:
  238. @code
  239. @class YYShadow, YYBorder, YYAttachment;
  240. @interface YYAttributes
  241. @property NSString *name;
  242. @property NSArray *shadows;
  243. @property NSSet *borders;
  244. @property NSDictionary *attachments;
  245. @end
  246. @implementation YYAttributes
  247. + (NSDictionary *)modelContainerPropertyGenericClass {
  248. return @{@"shadows" : [YYShadow class],
  249. @"borders" : YYBorder.class,
  250. @"attachments" : @"YYAttachment" };
  251. }
  252. @end
  253. @endcode
  254. @return A class mapper.
  255. */
  256. + (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass;
  257. /**
  258. If you need to create instances of different classes during json->object transform,
  259. use the method to choose custom class based on dictionary data.
  260. @discussion If the model implements this method, it will be called to determine resulting class
  261. during `+modelWithJSON:`, `+modelWithDictionary:`, conveting object of properties of parent objects
  262. (both singular and containers via `+modelContainerPropertyGenericClass`).
  263. Example:
  264. @code
  265. @class YYCircle, YYRectangle, YYLine;
  266. @implementation YYShape
  267. + (Class)modelCustomClassForDictionary:(NSDictionary*)dictionary {
  268. if (dictionary[@"radius"] != nil) {
  269. return [YYCircle class];
  270. } else if (dictionary[@"width"] != nil) {
  271. return [YYRectangle class];
  272. } else if (dictionary[@"y2"] != nil) {
  273. return [YYLine class];
  274. } else {
  275. return [self class];
  276. }
  277. }
  278. @end
  279. @endcode
  280. @param dictionary The json/kv dictionary.
  281. @return Class to create from this dictionary, `nil` to use current class.
  282. */
  283. + (nullable Class)modelCustomClassForDictionary:(NSDictionary *)dictionary;
  284. /**
  285. All the properties in blacklist will be ignored in model transform process.
  286. Returns nil to ignore this feature.
  287. @return An array of property's name.
  288. */
  289. + (nullable NSArray<NSString *> *)modelPropertyBlacklist;
  290. /**
  291. If a property is not in the whitelist, it will be ignored in model transform process.
  292. Returns nil to ignore this feature.
  293. @return An array of property's name.
  294. */
  295. + (nullable NSArray<NSString *> *)modelPropertyWhitelist;
  296. /**
  297. This method's behavior is similar to `- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;`,
  298. but be called before the model transform.
  299. @discussion If the model implements this method, it will be called before
  300. `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`.
  301. If this method returns nil, the transform process will ignore this model.
  302. @param dic The json/kv dictionary.
  303. @return Returns the modified dictionary, or nil to ignore this model.
  304. */
  305. - (NSDictionary *)modelCustomWillTransformFromDictionary:(NSDictionary *)dic;
  306. /**
  307. If the default json-to-model transform does not fit to your model object, implement
  308. this method to do additional process. You can also use this method to validate the
  309. model's properties.
  310. @discussion If the model implements this method, it will be called at the end of
  311. `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`.
  312. If this method returns NO, the transform process will ignore this model.
  313. @param dic The json/kv dictionary.
  314. @return Returns YES if the model is valid, or NO to ignore this model.
  315. */
  316. - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;
  317. /**
  318. If the default model-to-json transform does not fit to your model class, implement
  319. this method to do additional process. You can also use this method to validate the
  320. json dictionary.
  321. @discussion If the model implements this method, it will be called at the end of
  322. `-modelToJSONObject` and `-modelToJSONString`.
  323. If this method returns NO, the transform process will ignore this json dictionary.
  324. @param dic The json dictionary.
  325. @return Returns YES if the model is valid, or NO to ignore this model.
  326. */
  327. - (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic;
  328. @end
  329. NS_ASSUME_NONNULL_END