CLKModel
为您的 Cocoa 应用程序的数据类型提供了一个优秀的基类。
CLKModel
可以处理与 JSON
之间的解析,包括对后续 CLKModel
子类和数组的泛型类型的嵌套解析。这是通过在运行时对属性类型的动态自省,配合一个简单提供键和属性之间映射的 blueprint
实现的。
CLKModel
还提供了将特定属性存储到磁盘的功能,既可以使用 NSUserDefaults
,也可以使用 Apple 的 Security
框架。此功能将任何 CLKModels
作为 NSDictionary
存储,自动充气并放气。
这是一个简单的 CLKModel
子类实例
@interface Person : CLKModel
@property (atomic, copy) NSString *firstName;
@property (atomic, strong) NSDate *dateOfBirth;
@property (atomic, assign) CGFloat heightInMeters;
@end
@implementation Person
+ (NSDictionary *)blueprint
{
return @{
@"first_name" : @"firstName",
@"dob" : @"dateOfBirth",
@"height" : @"heightInMeters"
};
}
@end
现在可以像这样充气和放气
NSDictionary *personInfo = @{
@"first_name" : @"John",
@"dob" : @(635908156000),
@"height" : @(1.83)
};
Person *person = [[Person alloc] initFromJSON:personInfo];
NSDictionary *personInfoOut = [person toJSON];
personInfo
现在等于 personInfoOut
。
CLKModel
支持
NSString
NSArray
NSDictionary
int
、float
、double
、NSInteger
等.)NSDate
作为自纪元以来的毫秒数提供的 NSNumber
或 NSString
CLKModel
子类如果您有一个包含原始类型或字符串的 JSON 数组,可以无需额外的代码进行解析。如果数组包含您想解析为后续 CLKModels
的 JSON,只需在您的设计中定义以下泛型
+ (NSDictionary *)blueprint
{
return @{
@"comments": @{
@"is_array": @YES,
@"property": @"comments",
@"class": @"Comment"
}
}
此类现在可以递归地充气和放气评论数组,作为 Comment
模型实例,Comment
本身是具有自己设计图的 CLKModel
子类。棒极了!
要将属性持久化到磁盘,您需要一个集合类是 singleton,这样在重新初始化时可以一致地重新充气字段,而不会发生命名空间冲突。持久化可以是到 NSUserDefaults
或系统密钥链。以下是一个简单的例子
@interface Contacts
DECLARE_SINGLETON_FOR_CLASS(Contacts)
@property (nonatomic, strong) NSArray *relevantContacts;
@property (nonatomic, assign) NSInteger numTimesContactsHaveRefreshed;
@property (nonatomic, copy) NSString *contactsAccessToken;
@end
@implementation Contacts
SYNTHESIZE_SINGLETON_FOR_CLASS(Contacts)
+ (NSArray *)defaultsBackedProperties
{
return @[@"relevantContacts",
@"numTimesContactsHaveRefreshed"];
}
+ (NSArray *)keychainBackedProperties
{
return @[
@"contactsAccessToken"
];
}
+ (NSDictionary *)genericTypesForBackedProperties
{
return @{@"relevantContacts": @"Person"};
}
@end
任何后端属性的设置器都会导致正确的序列化和写入磁盘。注意,CLKSingletons 不是 CLKModel 的依赖项,任何 singleton 或集合类方案都可行。
设置任何后端属性后,下一个 Contacts
实例将使用这些字段正确反序列化并设置到相应的属性中。说实话,这相当棒。