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
如果我们需要处理的情况符合下面两个要求:
- Model类的个数比较少
- 每个Model的成员不是很复杂
这种情况下使用上述方法还可以接受。但是一旦Model这一层急剧膨胀,这时候就会让人苦不堪言:
- initWithAttributes函数容易写错,而且出错后不方便排查。
- 机械性的代码会比较多,不利于提高效率。
考虑到手动转JSON为Model的种种不
自定义实现JSON到Model转换的Objective-C库

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

被折叠的 条评论
为什么被折叠?



