催化 1.0.2

催化 1.0.2

测试已测试
Lang语言 Obj-CObjective C
许可证 Apache 2
发布上次发布2015年11月

Patrick Hogan 维护。



催化 1.0.2

  • Patrick Hogan

什么是催化?

Catalytic 提供了一种简单地将 JSON 数据映射到本地的 Objective-C 领域对象的方式。

要求

  • iOS 9.0+ / Mac OS X 10.10+
  • Xcode 7.0
  • Cocoapods 0.37.1

使用方法

以下是一些领域对象示例,即 ModelObjectNestedObject

//  ModelObject.h

#import <Foundation/Foundation.h>

@class NestedObject;

@interface ModelObject : NSObject

@property (nonatomic, readonly) NSArray<NSString *> *strings;
@property (nonatomic, readonly) NestedObject *nestedObject;
@property (nonatomic, readonly) NSArray<NestedObject *> *nestedObjects;

@end
//  NestedObject.h

#import <Foundation/Foundation.h>

@interface NestedObject : NSObject

@property (nonatomic, readonly, copy) NSString *string;
@property (nonatomic, readonly) NSInteger integer;

@end

Catalytic 可以轻松地将这些对象的相应 JSON 表示映射到上面给出的本地字段。

{
    "type": "model_object",
    "nested_object": {
        "type": "nested_object",
        "string": "0",
        "integer": 0
    },
    "nested_objects": [
        {
            "type": "nested_object",
            "string": "1",
            "integer": 1
        },
        {
            "type": "nested_object",
            "string": "2",
            "integer": 2
        }
    ],
    "strings": [
        "abc",
        "bbd"
    ]
}

首先设置一个 id <CTTypeProvider> 实例来处理包含字典到领域对象类的映射。

//  TypeProvider.m

#import "TypeProvider.h"

#import "ModelObject.h"
#import "NestedObject.h"

@implementation TypeProvider

- (Class)typeOfObject:(id)object
       containerClass:(__unsafe_unretained Class)containerClass
       referencingKey:(NSString *)key
            fieldType:(CTConverterFieldType)fieldType {

    if ([[object valueForKey:@"type"] isEqualToString:@"model_object"]) {
        return [ModelObject class];
    } else if ([[object valueForKey:@"type"] isEqualToString:@"nested_object"]) {
        return [NestedObject class];
    } else {
        return NULL;
    }

}

@end

然后从给定的 JSON 中恢复解析后的领域对象是一个简单的过程。

id <CTTypeProvider> typeProvider = [[TypeProvider alloc] init];
CTConverter *converter = [[CTConverter alloc] initWithFieldNamingPolicy:CTConverterFieldNamingPolicyLowerCaseWithUnderscores
                                                           typeProvider:typeProvider];

NSDictionary *jsonDictionary = ({
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"model_object" ofType:@"json"];
    NSData *jsonData = [[NSData alloc] initWithContentsOfFile:jsonPath];
    [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
});

NSError * __autoreleasing error;
ModelObject *modelObject = [converter convert:jsonDictionary error:&error];