免费开源的iOS开发学习平台

YYModel:2-YYModel使用

本节通过一个简单的案例介绍YYModel的简单使用,包括使用YYModel的字典转模型、模型转JSON以及JSON转模型的使用方法。

准备工作

首先使用CocoaPods导入YYModel框架。

在工程中,新建一个WebSite类,并在其中添加3个属性。

@interface WebSite : NSObject
@property (nonatomic,copy) NSString *url;
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSNumber *foundedYear;
@end

使用YYModel进行模型转换

在下方的方法中,我们首先创建了一个字典对象,并添加了3个键值对,然后使用YYModel中的字典转模型的方法,把字典对象转换为模型对象。而后使用YYModel中提供的方法实现了模型与JSON的互转。

-(void) YYModleTest {
    //创建原始字典
    NSDictionary *dict = @{
                           @"url":@"www.99ios.com",
                           @"name":@"九九学院",
                           @"foundedYear":@2016
                           };
    //字典转模型
    WebSite *webSite1 = [WebSite yy_modelWithDictionary:dict];
    NSLog(@"-----字典转模型-----");
    NSLog(@"url:%@, name:%@, foundedYear:%@",webSite1.url,webSite1.name,webSite1.foundedYear);
    //模型转json
    NSDictionary *json = [webSite1 yy_modelToJSONObject];
    NSLog(@"-----模型转json-----");
    NSLog(@"%@",json);
    //json转模型
    WebSite *webSite2 = [WebSite yy_modelWithJSON:json];
    NSLog(@"-----json转模型-----");
    NSLog(@"url:%@, name:%@, foundedYear:%@",webSite2.url,webSite2.name,webSite2.foundedYear);
}

调用该方法后,通过日志可以查看模型转换的结果。