MJExtension的使用

Posted jeikerxiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MJExtension的使用相关的知识,希望对你有一定的参考价值。

前言

MJExtension是一套“字典和模型之间互相转换”的轻量级框架

MJExtension能完成的功能

  • 字典 –> 模型
  • 模型 –> 字典
  • 字典数组 –> 模型数组
  • 模型数组 –> 字典数组

    具体用法主要参考 “NSObject+MJKeyValue.h”


实例

1.简单的字典 -> 模型

//
//  MJUser.h
//  字典与模型的互转
//  用户模型
//

#import <Foundation/Foundation.h>

typedef enum {
    SexMale,
    SexFemale
} Sex;

@interface MJUser : NSObject
/** 名称 */
@property (copy, nonatomic) NSString *name;
/** 头像 */
@property (copy, nonatomic) NSString *icon;
/** 年龄 */
@property (assign, nonatomic) unsigned int age;
/** 身高 */
@property (strong, nonatomic) NSNumber *height;
/** 财富 */
@property (strong, nonatomic) NSDecimalNumber *money;
/** 性别 */
@property (assign, nonatomic) Sex sex;
/** 同性恋 */
@property (assign, nonatomic, getter=isGay) BOOL gay;

@end
/**
 *  简单的字典 -> 模型
 */
void keyValues2object()
{
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"name" : @"Jack",
                           @"icon" : @"lufy.png",
                           @"age" : @"20",
                           @"height" : @1.55,
                           @"money" : @"100.9",
                           @"sex" : @(SexFemale),
                           @"gay" : @"1"
                       //  @"gay" : @"NO"
                       //  @"gay" : @"true"
                           };

    // 2.将字典转为MJUser模型
    MJUser *user = [MJUser mj_objectWithKeyValues:dict];

    // 3.打印MJUser模型的属性
    MJExtensionLog(@"name=%@, icon=%@, age=%zd, height=%@, money=%@, sex=%d, gay=%d", user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay);
}

2.JSON字符串 -> 模型

/**
 *  JSON字符串 -> 模型
 */
void keyValues2object1()
{
    // 1.定义一个JSON字符串
    NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20, \"height\":333333.7}";

    // 2.将JSON字符串转为MJUser模型
    MJUser *user = [MJUser mj_objectWithKeyValues:jsonString];

    // 3.打印MJUser模型的属性
    MJExtensionLog(@"name=%@, icon=%@, age=%d, height=%@", user.name, user.icon, user.age, user.height);
}

3.复杂的字典 -> 模型 (模型里面包含了模型)

//
//  MJStatus.h
//  字典与模型的互转
//  微博模型
//

#import <Foundation/Foundation.h>
@class MJUser;

@interface MJStatus : NSObject
/** 微博文本内容 */
@property (copy, nonatomic) NSString *text;
/** 微博作者 */
@property (strong, nonatomic) MJUser *user;
/** 转发的微博 */
@property (strong, nonatomic) MJStatus *retweetedStatus;

@end
/**
 *  复杂的字典 -> 模型 (模型里面包含了模型)
 */
void keyValues2object2()
{
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"text" : @"是啊,今天天气确实不错!",

                           @"user" : @{
                                   @"name" : @"Jack",
                                   @"icon" : @"lufy.png"
                                   },

                           @"retweetedStatus" : @{
                                   @"text" : @"今天天气真不错!",

                                   @"user" : @{
                                           @"name" : @"Rose",
                                           @"icon" : @"nami.png"
                                           }
                                   }
                           };

    // 2.将字典转为Status模型
    MJStatus *status = [MJStatus mj_objectWithKeyValues:dict];

    // 3.打印status的属性
    NSString *text = status.text;
    NSString *name = status.user.name;
    NSString *icon = status.user.icon;
    MJExtensionLog(@"text=%@, name=%@, icon=%@", text, name, icon);

    // 4.打印status.retweetedStatus的属性
    NSString *text2 = status.retweetedStatus.text;
    NSString *name2 = status.retweetedStatus.user.name;
    NSString *icon2 = status.retweetedStatus.user.icon;
    MJExtensionLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
}

4.复杂的字典 -> 模型 (模型的数组属性里面又装着模型)

//
//  MJStatusResult.h
//  字典与模型的互转
//  微博结果(用来表示大批量的微博数据)
//

#import "MJBaseObject.h"

@interface MJStatusResult : MJBaseObject
/** 存放着某一页微博数据(里面都是Status模型) */
@property (strong, nonatomic) NSMutableArray *statuses;
/** 存放着一堆的广告数据(里面都是MJAd模型) */
@property (strong, nonatomic) NSArray *ads;
/** 总数 */
@property (strong, nonatomic) NSNumber *totalNumber;
/** 上一页的游标 */
@property (assign, nonatomic) long long previousCursor;
/** 下一页的游标 */
@property (assign, nonatomic) long long nextCursor;

@end
//
//  MJStatusResult.m
//  字典与模型的互转
//

#import "MJStatusResult.h"

@implementation MJStatusResult

+ (NSDictionary *)mj_objectClassInArray
{
    return @{
             @"statuses" : @"MJStatus",
             @"ads" : @"MJAd"
             };
}

@end
/**
 *  复杂的字典 -> 模型 (模型的数组属性里面又装着模型)
 */
void keyValues2object3()
{
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"statuses" : @[
                                   @{
                                       @"text" : @"今天天气真不错!",

                                       @"user" : @{
                                               @"name" : @"Rose",
                                               @"icon" : @"nami.png"
                                               }
                                       },

                                   @{
                                       @"text" : @"明天去旅游了",

                                       @"user" : @{
                                               @"name" : @"Jack",
                                               @"icon" : @"lufy.png"
                                               }
                                       }

                                   ],

                           @"ads" : @[
                                   @{
                                       @"image" : @"ad01.png",
                                       @"url" : @"http://www.小码哥ad01.com"
                                       },
                                   @{
                                       @"image" : @"ad02.png",
                                       @"url" : @"http://www.小码哥ad02.com"
                                       }
                                   ],

                           @"totalNumber" : @"2014",
                           @"previousCursor" : @"13476589",
                           @"nextCursor" : @"13476599"
                           };

    // 2.将字典转为MJStatusResult模型
    MJStatusResult *result = [MJStatusResult mj_objectWithKeyValues:dict];

    // 3.打印MJStatusResult模型的简单属性
    MJExtensionLog(@"totalNumber=%@, previousCursor=%lld, nextCursor=%lld", result.totalNumber, result.previousCursor, result.nextCursor);

    // 4.打印statuses数组中的模型属性
    for (MJStatus *status in result.statuses) {
        NSString *text = status.text;
        NSString *name = status.user.name;
        NSString *icon = status.user.icon;
        MJExtensionLog(@"text=%@, name=%@, icon=%@", text, name, icon);
    }

    // 5.打印ads数组中的模型属性
    for (MJAd *ad in result.ads) {
        MJExtensionLog(@"image=%@, url=%@", ad.image, ad.url);
    }
}

5.简单的字典 -> 模型(key替换,比如ID和id,支持多级映射)

//
//  MJStudent.h
//  MJExtensionExample
//

#import <Foundation/Foundation.h>
@class MJBag;

@interface MJStudent : NSObject

@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *otherName;
@property (copy, nonatomic) NSString *nowName;
@property (copy, nonatomic) NSString *oldName;
@property (copy, nonatomic) NSString *nameChangedTime;
@property (copy, nonatomic) NSString *desc;
@property (strong, nonatomic) MJBag *bag;
@property (strong, nonatomic) NSArray *books;

@end
/**
 * 简单的字典 -> 模型(key替换,比如ID和id。多级映射,比如 oldName 和 name.oldName)
 */
void keyValues2object4()
{
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"id" : @"20",
                           @"desciption" : @"好孩子",
                           @"name" : @{
                                   @"newName" : @"lufy",
                                   @"oldName" : @"kitty",
                                   @"info" : @[
                                           @"test-data",
                                           @{@"nameChangedTime" : @"2013-08-07"}
                                           ]
                                   },
                           @"other" : @{
                                   @"bag" : @{
                                           @"name" : @"小书包",
                                           @"price" : @100.7
                                           }
                                   }
                           };

    // 2.将字典转为MJStudent模型
    MJStudent *stu = [MJStudent mj_objectWithKeyValues:dict];

    // 3.打印MJStudent模型的属性
    MJExtensionLog(@"ID=%@, desc=%@, otherName=%@, oldName=%@, nowName=%@, nameChangedTime=%@", stu.ID, stu.desc, stu.otherName, stu.oldName, stu.nowName, stu.nameChangedTime);
    MJExtensionLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);

    //    CFTimeInterval begin = CFAbsoluteTimeGetCurrent();
    //    for (int i = 0; i< 10000; i++) {
    //        [MJStudent mj_objectWithKeyValues:dict];
    //    }
    //    CFTimeInterval end = CFAbsoluteTimeGetCurrent();
    //    MJExtensionLog(@"%f", end - begin);
}

6.字典数组 -> 模型数组

//
//  MJUser.h
//  字典与模型的互转
//  用户模型

#import <Foundation/Foundation.h>

typedef enum {
    SexMale,
    SexFemale
} Sex;

@interface MJUser : NSObject
/** 名称 */
@property (copy, nonatomic) NSString *name;
/** 头像 */
@property (copy, nonatomic) NSString *icon;
/** 年龄 */
@property (assign, nonatomic) unsigned int age;
/** 身高 */
@property (strong, nonatomic) NSNumber *height;
/** 财富 */
@property (strong, nonatomic) NSDecimalNumber *money;
/** 性别 */
@property (assign, nonatomic) Sex sex;
/** 同性恋 */
@property (assign, nonatomic, getter=isGay) BOOL gay;

@end
/**
 *  字典数组 -> 模型数组
 */
void keyValuesArray2objectArray()
{
    // 1.定义一个字典数组
    NSArray *dictArray = @[
                           @{
                               @"name" : @"Jack",
                               @"icon" : @"lufy.png",
                               },

                           @{
                               @"name" : @"Rose",
                               @"icon" : @"nami.png",
                               }
                           ];

    // 2.将字典数组转为MJUser模型数组
    NSArray *userArray = [MJUser mj_objectArrayWithKeyValuesArray:dictArray];

    // 3.打印userArray数组中的MJUser模型属性
    for (MJUser *user in userArray) {
        MJExtensionLog(@"name=%@, icon=%@", user.name, user.icon);
    }
}

7.模型转字典

/**
 *  模型 -> 字典
 */
void object2keyValues()
{
    // 1.新建模型
    MJUser *user = [[MJUser alloc] init];
    user.name = @"Jack";
    user.icon = @"lufy.png";

    MJStatus *status = [[MJStatus alloc] init];
    status.user = user;
    status.text = @"今天的心情不错!";

    // 2.将模型转为字典
    NSDictionary *statusDict = status.mj_keyValues;
    MJExtensionLog(@"%@", statusDict);

    MJExtensionLog(@"%@", [status mj_keyValuesWithKeys:@[@"text"]]);

    // 3.新建多级映射的模型
    MJStudent *stu = [[MJStudent alloc] init];
    stu.ID = @"123";
    stu.oldName = @"rose";
    stu.nowName = @"jack";
    stu.desc = @"handsome";
    stu.nameChangedTime = @"2018-09-08";
    stu.books = @[@"Good book", @"Red book"];

    MJBag *bag = [[MJBag alloc] init];
    bag.name = @"小书包";
    bag.price = 205;
    stu.bag = bag;

    NSDictionary *stuDict = stu.mj_keyValues;
    MJExtensionLog(@"%@", stuDict);
    MJExtensionLog(@"%@", [stu mj_keyValuesWithIgnoredKeys:@[@"bag", @"oldName", @"nowName"]]);
    MJExtensionLog(@"%@", stu.mj_JSONString);

    [MJStudent mj_referenceReplacedKeyWhenCreatingKeyValues:NO];
    MJExtensionLog(@"\n模型转字典时,字典的key参考replacedKeyFromPropertyName等方法:\n%@", stu.mj_keyValues);
}

8.模型数组 -> 字典数组

/**
 *  模型数组 -> 字典数组
 */
void objectArray2keyValuesArray()
{
    // 1.新建模型数组
    MJUser *user1 = [[MJUser alloc] init];
    user1.name = @"Jack";
    user1.icon = @"lufy.png";

    MJUser *user2 = [[MJUser alloc] init];
    user2.name = @"Rose";
    user2.icon = @"nami.png";

    NSArray *userArray = @[user1, user2];

    // 2.将模型数组转为字典数组
    NSArray *dictArray = [MJUser mj_keyValuesArrayWithObjectArray:userArray];
    MJExtensionLog(@"%@", dictArray);
}

9.CoreData示例

/**
 *  CoreData示例
 */
void coreData()
{
    NSDictionary *dict = @{
                           @"name" : @"Jack",
                           @"icon" : @"lufy.png",
                           @"age" : @20,
                           @"height" : @1.55,
                           @"money" : @"100.9",
                           @"sex" : @(SexFemale),
                           @"gay" : @"true"
                           };

    // 这个Demo仅仅提供思路,具体的方法参数需要自己创建
    NSManagedObjectContext *context = nil;
    MJUser *user = [MJUser mj_objectWithKeyValues:dict context:context];

    // 利用CoreData保存模型
    [context save:nil];

    MJExtensionLog(@"name=%@, icon=%@, age=%zd, height=%f, money=%@, sex=%d, gay=%d", user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay);
}

10.NSCoding示例

//
//  MJBag.h
//  MJExtensionExample
//

#import <Foundation/Foundation.h>

@interface MJBag : NSObject

@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) double price;

@end
//
//  MJBag.m
//  MJExtensionExample
//

#import "MJBag.h"
#import "MJExtension.h"

@implementation MJBag
// NSCoding实现
MJExtensionCodingImplementation

//+ (NSArray *)mj_ignoredCodingPropertyNames
//{
//    return @[@"name"];
//}

@end
/**
 * NSCoding示例
 */
void coding()
{
    // 创建模型
    MJBag *bag = [[MJBag alloc] init];
    bag.name = @"Red bag";
    bag.price = 200.8;

    NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bag.data"];
    // 归档
    [NSKeyedArchiver archiveRootObject:bag toFile:file];

    // 解档
    MJBag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
    MJExtensionLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);
}

11.统一转换属性名(比如驼峰转下划线)

/**
 *  统一转换属性名(比如驼峰转下划线)
 */
void replacedKeyFromPropertyName121()
{
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"nick_name" : @"旺财",
                           @"sale_price" : @"10.5",
                           @"run_speed" : @"100.9"
                           };

    // 2.将字典转为MJUser模型
    MJDog *dog = [MJDog mj_objectWithKeyValues:dict];

    // 3.打印MJUser模型的属性
    MJExtensionLog(@"nickName=%@, scalePrice=%f runSpeed=%f", dog.nickName, dog.salePrice, dog.runSpeed);
}

12.过滤字典的值(比如字符串日期处理为NSDate、字符串nil处理为@”“)

//
//  MJDog.h
//  MJExtensionExample
//

#import <Foundation/Foundation.h>

@interface MJDog : NSObject

@property (copy, nonatomic) NSString *nickName;
@property (assign, nonatomic) double salePrice;
@property (assign, nonatomic) double runSpeed;

@end
/**
 *  过滤字典的值(比如字符串日期处理为NSDate、字符串nil处理为@"")
 */
void newValueFromOldValue()
{
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"name" : @"5分钟突破ios开发",
                           @"publishedTime" : @"2011-09-10"
                           };

    // 2.将字典转为MJUser模型
    MJBook *book = [MJBook mj_objectWithKeyValues:dict];

    // 3.打印MJUser模型的属性
    MJExtensionLog(@"name=%@, publisher=%@, publishedTime=%@", book.name, book.publisher, book.publishedTime);
}

以上是关于MJExtension的使用的主要内容,如果未能解决你的问题,请参考以下文章

MJExtension框架源码分析

MJExtension常用方法

MJExtension使用

MJExtension的使用

使用MJExtension遇到的问题和注意

OC中第三方库MJExtension的使用