无标题文章

//
// NSObject+YYModel.h
// YYModel https://github.com/ibireme/YYModel
//
// Created by ibireme on 15/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 <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

/**
Provide some data-model method:

  • Convert json to any object, or convert any object to json.
  • Set object properties with a key-value dictionary (like KVC).
  • Implementations of NSCoding, NSCopying, -hash and -isEqual:.

See YYModel protocol for custom methods.

Sample Code:

 ********************** json convertor *********************
 @interface YYAuthor : NSObject
 @property (nonatomic, strong) NSString *name;
 @property (nonatomic, assign) NSDate *birthday;
 @end
 @implementation YYAuthor
 @end

 @interface YYBook : NSObject
 @property (nonatomic, copy) NSString *name;
 @property (nonatomic, assign) NSUInteger pages;
 @property (nonatomic, strong) YYAuthor *author;
 @end
 @implementation YYBook
 @end

 int main() {
     // create model from json
     YYBook *book = [YYBook yy_modelWithJSON:@"{\"name\": \"Harry Potter\", \"pages\": 256, \"author\": {\"name\": \"J.K.Rowling\", \"birthday\": \"1965-07-31\" }}"];

     // convert model to json
     NSString *json = [book yy_modelToJSONString];
     // {"author":{"name":"J.K.Rowling","birthday":"1965-07-31T00:00:00+0000"},"name":"Harry Potter","pages":256}
 }

 ********************** Coding/Copying/hash/equal *********************
 @interface YYShadow :NSObject <NSCoding, NSCopying>
 @property (nonatomic, copy) NSString *name;
 @property (nonatomic, assign) CGSize size;
 @end

 @implementation YYShadow
 - (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
 - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
 - (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; }
 - (NSUInteger)hash { return [self yy_modelHash]; }
 - (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; }
 @end

*/
@interface NSObject (YYModel)

/**
Creates and returns a new instance of the receiver from a json.
This method is thread-safe.

@param json A json object in NSDictionary, NSString or NSData.

@return A new instance created from the json, or nil if an error occurs.
*/

  • (nullable instancetype)yy_modelWithJSON:(id)json;

/**
Creates and returns a new instance of the receiver from a key-value dictionary.
This method is thread-safe.

@param dictionary A key-value dictionary mapped to the instance's properties.
Any invalid key-value pair in dictionary will be ignored.

@return A new instance created from the dictionary, or nil if an error occurs.

@discussion The key in dictionary will mapped to the reciever's property name,
and the value will set to the property. If the value's type does not match the
property, this method will try to convert the value based on these rules:

 `NSString` or `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger...
 `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd".
 `NSString` -> NSURL.
 `NSValue` -> struct or union, such as CGRect, CGSize, ...
 `NSString` -> SEL, Class.

*/

  • (nullable instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary;

/**
Set the receiver's properties with a json object.

@discussion Any invalid data in json will be ignored.

@param json A json object of NSDictionary, NSString or NSData, mapped to the
receiver's properties.

@return Whether succeed.
*/

  • (BOOL)yy_modelSetWithJSON:(id)json;

/**
Set the receiver's properties with a key-value dictionary.

@param dic A key-value dictionary mapped to the receiver's properties.
Any invalid key-value pair in dictionary will be ignored.

@discussion The key in dictionary will mapped to the reciever's property name,
and the value will set to the property. If the value's type doesn't match the
property, this method will try to convert the value based on these rules:

 `NSString`, `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger...
 `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd".
 `NSString` -> NSURL.
 `NSValue` -> struct or union, such as CGRect, CGSize, ...
 `NSString` -> SEL, Class.

@return Whether succeed.
*/

  • (BOOL)yy_modelSetWithDictionary:(NSDictionary *)dic;

/**
Generate a json object from the receiver's properties.

@return A json object in NSDictionary or NSArray, or nil if an error occurs.
See [NSJSONSerialization isValidJSONObject] for more information.

@discussion Any of the invalid property is ignored.
If the reciver is NSArray, NSDictionary or NSSet, it just convert
the inner object to json object.
*/

  • (nullable id)yy_modelToJSONObject;

/**
Generate a json string's data from the receiver's properties.

@return A json string's data, or nil if an error occurs.

@discussion Any of the invalid property is ignored.
If the reciver is NSArray, NSDictionary or NSSet, it will also convert the
inner object to json string.
*/

  • (nullable NSData *)yy_modelToJSONData;

/**
Generate a json string from the receiver's properties.

@return A json string, or nil if an error occurs.

@discussion Any of the invalid property is ignored.
If the reciver is NSArray, NSDictionary or NSSet, it will also convert the
inner object to json string.
*/

  • (nullable NSString *)yy_modelToJSONString;

/**
Copy a instance with the receiver's properties.

@return A copied instance, or nil if an error occurs.
*/

  • (nullable id)yy_modelCopy;

/**
Encode the receiver's properties to a coder.

@param aCoder An archiver object.
*/

  • (void)yy_modelEncodeWithCoder:(NSCoder *)aCoder;

/**
Decode the receiver's properties from a decoder.

@param aDecoder An archiver object.

@return self
*/

  • (id)yy_modelInitWithCoder:(NSCoder *)aDecoder;

/**
Get a hash code with the receiver's properties.

@return Hash code.
*/

  • (NSUInteger)yy_modelHash;

/**
Compares the receiver with another object for equality, based on properties.

@param model Another object.

@return YES if the reciever is equal to the object, otherwise NO.
*/

  • (BOOL)yy_modelIsEqual:(id)model;

/**
Description method for debugging purposes based on properties.

@return A string that describes the contents of the receiver.
*/

  • (NSString *)yy_modelDescription;

@end

/**
Provide some data-model method for NSArray.
*/
@interface NSArray (YYModel)

/**
Creates and returns an array from a json-array.
This method is thread-safe.

@param cls The instance's class in array.
@param json A json array of NSArray, NSString or NSData.
Example: [{"name","Mary"},{name:"Joe"}]

@return A array, or nil if an error occurs.
*/

  • (nullable NSArray *)yy_modelArrayWithClass:(Class)cls json:(id)json;

@end

/**
Provide some data-model method for NSDictionary.
*/
@interface NSDictionary (YYModel)

/**
Creates and returns a dictionary from a json.
This method is thread-safe.

@param cls The value instance's class in dictionary.
@param json A json dictionary of NSDictionary, NSString or NSData.
Example: {"user1":{"name","Mary"}, "user2": {name:"Joe"}}

@return A array, or nil if an error occurs.
*/

  • (nullable NSDictionary *)yy_modelDictionaryWithClass:(Class)cls json:(id)json;
    @end

/**
If the default model transform does not fit to your model class, implement one or
more method in this protocol to change the default key-value transform process.
There's no need to add '<YYModel>' to your class header.
*/
@protocol YYModel <NSObject>
@optional

/**
Custom property mapper.

@discussion If the key in JSON/Dictionary does not match to the model's property name,
implements this method and returns the additional mapper.

Example:

json: 
    {
        "n":"Harry Pottery",
        "p": 256,
        "ext" : {
            "desc" : "A book written by J.K.Rowling."
        },
        "ID" : 100010
    }

model:
    @interface YYBook : NSObject
    @property NSString *name;
    @property NSInteger page;
    @property NSString *desc;
    @property NSString *bookID;
    @end
    
    @implementation YYBook
    + (NSDictionary *)modelCustomPropertyMapper {
        return @{@"name"  : @"n",
                 @"page"  : @"p",
                 @"desc"  : @"ext.desc",
                 @"bookID": @[@"id", @"ID", @"book_id"]};
    }
    @end

@return A custom mapper for properties.
*/

  • (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper;

/**
The generic class mapper for container properties.

@discussion If the property is a container object, such as NSArray/NSSet/NSDictionary,
implements this method and returns a property->class mapper, tells which kind of
object will be add to the array/set/dictionary.

Example:
@class YYShadow, YYBorder, YYAttachment;

    @interface YYAttributes
    @property NSString *name;
    @property NSArray *shadows;
    @property NSSet *borders;
    @property NSDictionary *attachments;
    @end

    @implementation YYAttributes
    + (NSDictionary *)modelContainerPropertyGenericClass {
        return @{@"shadows" : [YYShadow class],
                 @"borders" : YYBorder.class,
                 @"attachments" : @"YYAttachment" };
    }
    @end

@return A class mapper.
*/

  • (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass;

/**
If you need to create instances of different classes during json->object transform,
use the method to choose custom class based on dictionary data.

@discussion If the model implements this method, it will be called to determine resulting class
during +modelWithJSON:, +modelWithDictionary:, conveting object of properties of parent objects
(both singular and containers via +modelContainerPropertyGenericClass).

Example:
@class YYCircle, YYRectangle, YYLine;

    @implementation YYShape

    + (Class)modelCustomClassForDictionary:(NSDictionary*)dictionary {
        if (dictionary[@"radius"] != nil) {
            return [YYCircle class];
        } else if (dictionary[@"width"] != nil) {
            return [YYRectangle class];
        } else if (dictionary[@"y2"] != nil) {
            return [YYLine class];
        } else {
            return [self class];
        }
    }

    @end

@param dictionary The json/kv dictionary.

@return Class to create from this dictionary, nil to use current class.

*/

  • (nullable Class)modelCustomClassForDictionary:(NSDictionary *)dictionary;

/**
All the properties in blacklist will be ignored in model transform process.
Returns nil to ignore this feature.

@return An array of property's name.
*/

  • (nullable NSArray<NSString *> *)modelPropertyBlacklist;

/**
If a property is not in the whitelist, it will be ignored in model transform process.
Returns nil to ignore this feature.

@return An array of property's name.
*/

  • (nullable NSArray<NSString *> *)modelPropertyWhitelist;

/**
This method's behavior is similar to - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;,
but be called before the model transform.

@discussion If the model implements this method, it will be called before
+modelWithJSON:, +modelWithDictionary:, -modelSetWithJSON: and -modelSetWithDictionary:.
If this method returns nil, the transform process will ignore this model.

@param dic The json/kv dictionary.

@return Returns the modified dictionary, or nil to ignore this model.
*/

  • (NSDictionary *)modelCustomWillTransformFromDictionary:(NSDictionary *)dic;

/**
If the default json-to-model transform does not fit to your model object, implement
this method to do additional process. You can also use this method to validate the
model's properties.

@discussion If the model implements this method, it will be called at the end of
+modelWithJSON:, +modelWithDictionary:, -modelSetWithJSON: and -modelSetWithDictionary:.
If this method returns NO, the transform process will ignore this model.

@param dic The json/kv dictionary.

@return Returns YES if the model is valid, or NO to ignore this model.
*/

  • (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;

/**
If the default model-to-json transform does not fit to your model class, implement
this method to do additional process. You can also use this method to validate the
json dictionary.

@discussion If the model implements this method, it will be called at the end of
-modelToJSONObject and -modelToJSONString.
If this method returns NO, the transform process will ignore this json dictionary.

@param dic The json dictionary.

@return Returns YES if the model is valid, or NO to ignore this model.
*/

  • (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic;

@end

NS_ASSUME_NONNULL_END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,214评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,307评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,543评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,221评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,224评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,007评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,313评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,956评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,441评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,925评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,018评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,685评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,234评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,240评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,464评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,467评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,762评论 2 345

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,679评论 0 9
  • 源起九重天, 舞落山峰上。 天地潇潇然, 飞雪映孤城。
    村头一哥阅读 262评论 0 1
  • 2009年的春天与以往的春天没有任何的区别和差异,依旧艳阳高照,慢慢的变暖,春芽在大家的关注与不关注中慢慢的...
    小T的家阅读 306评论 0 1