【疯狂造轮子-iOS】JSON转Model系列之一

自定义实现JSON到Model转换的Objective-C库
文章介绍了作者在iOS开发中为提升个人技能,决定自己编写JSON到Model转换库的过程。作者分析了手动转换的不便,提出了设计思路,包括输入输出定义、核心算法以及具体实现。通过创建Category扩展NSObject,利用Runtime获取属性并调用setter方法。虽然目前实现简单,但存在如键值不一致、嵌套数据、非NSString值等问题待解决。

1. 前言


之前一直看别人的源码,虽然对自己提升比较大,但毕竟不是自己写的,很容易遗忘。这段时间准备自己造一些轮子,主要目的还是为了提升自身实力,总不能一遇到问题就Google

之前写i博客园客户端的时候,经常会遇到JSON数据转Model的功能。一般遇到这种问题我都是自己在对应Model类中定义一个+ (instance)initWithAttributes:(NSDictionary *)attributes函数来将NSDictionary*数据转化为对应Model。

下面是i博客园中ICUser的部分代码,其中就使用了initWithAttributes。

// ICUser.h
#import <Foundation/Foundation.h>
 
extern NSString *const kUserId;
extern NSString *const kUserBlogId;
extern NSString *const kUserDisplayName;
extern NSString *const kUserAvatarURL;
@interface ICUser : NSObject
 
@property (nonatomic, copy)     NSString    *userId;
@property (nonatomic, assign)   NSInteger   blogId;
@property (nonatomic, copy)     NSString    *displayName;
@property (nonatomic, strong)   NSURL       *avatarURL;

 + (instancetype)initWithAttributes:(NSDictionary *

)attributes;
 
@end
 
// ICUser.m
#import "ICUser.h"
 
NSString *const kUserId                 = @"UserId";
NSString *const kUserBlogId             = @"BlogId";
NSString *const kUserDisplayName        = @"DisplayName";
NSString *const kUserAvatarURL          = @"Avatar";
@implementation ICUser

+ (instancetype)initWithAttributes:(NSDictionary *

)attributes
{
    ICUser *user = [[ICUser alloc] init];
    user.userId             = attributes[kUserId];
    user.blogId             = [attributes[kUserBlogId] integerValue];
    user.displayName        = attributes[kUserDisplayName];
    user.avatarURL          = [NSURL URLWithString:attributes[kUserAvatarURL]];
return user;
}
 
@end

如果我们需要处理的情况符合下面两个要求:

  1. Model类的个数比较少
  2. 每个Model的成员不是很复杂

这种情况下使用上述方法还可以接受。但是一旦Model这一层急剧膨胀,这时候就会让人苦不堪言:

  1. initWithAttributes函数容易写错,而且出错后不方便排查。
  2. 机械性的代码会比较多,不利于提高效率。

考虑到手动转JSON为Model的种种不

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lmr廖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值