酷店

NSObject+YYModel.h 13KB

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