CoreData与Mantle的结合使用案例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Ginhoor/article/details/41821695
     Mantle(https://github.com/Mantle/Mantle)是一个用于操作CoreData的封装库。这个库的作用有两个,一是方便的对包含json数据的NSDictionary对象进行解析,并且使用其初始化对象。二是可以方便的将对象存储到CoreData中去。
     先说第一个功能点。首先你的类需要继承MTLModel,然后实现MTLJSONSerializing 这个协议。这个协议是用来定义如何处理传入的NSDictionary对象的。

#import <Mantle.h>
@interface EquipmentData : MTLModel<MTLJSONSerializing>

@property (copy, nonatomic, readonly) NSString *equipmentName;
@property (copy, nonatomic, readonly) NSString *equipmentLevel;

@end

     在m文件中需要实现 + (NSDictionary *)JSONKeyPathsByPropertyKey; 这个方法是Required实现的。这个方法的作用是将NSDictionary中键与EquipmentData中的property一一对应,如果两者名字相同,这无需注明。

例如:NSDictionary的数据是@{@“name”:@“武器一”,@“equipmentLevel”:@“等级一"}

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{@“equipmentName”:@“name”};//将Dictionary中“name”键值传入到“equipmentName”中,
}

然后,当你想创建新的EquipmentData时候,只需要按下面代码的形式就可以实现了。
    EquipmentData *data = [MTLJSONAdapter modelOfClass:[EquipmentData class] fromJSONDictionary:@{@“name”:@“武器一”,@“equipmentLevel”:@“等级一"} error:&error];

是不是简化了很多的json操作,但是问题还有,并不是所有的类型json都支持的,比如URL,NSDate等等,还有NSArray类型的属性存储的是自定义对象如何转化,在最后的demo项目中有具体的示范。



     现在介绍第二个功能点,将mantle对象存储到CoreData中。


为什么不用CoreData呢,这是Mantle官方给出的解答:

Why Not Use Core Data?
Core Data solves certain problems very well. If you need to execute complex queries across your data, handle a huge object graph with lots of relationships, or support undo and redo, Core Data is an excellent fit.
It does, however, come with a couple of pain points:
There's still a lot of boilerplate. Managed objects reduce some of the boilerplate seen above, but Core Data has plenty of its own. Correctly setting up a Core Data stack (with a persistent store and persistent store coordinator) and executing fetches can take many lines of code.
It's hard to get right. Even experienced developers can make mistakes when using Core Data, and the framework is not forgiving.
If you're just trying to access some JSON objects, Core Data can be a lot of work for little gain.
Nonetheless, if you're using or want to use Core Data in your app already, Mantle can still be a convenient translation layer between the API and your managed model objects.
     
首先接受下我们CoreData的Model文件

EquipmentData模型


PlayerData模型


这两个模型之间有一个一对多的关系,一个PlayerData对象有一多个equipments对象,一个EquipmentData属于一个PlayerData。 



在使用Mantle后,只需要在PlayerData.m文件中实现:

#pragma mark - CoreData

+ (NSString *)managedObjectEntityName
{
    return NSStringFromClass([self class]);
}

+ (NSDictionary *)managedObjectKeysByPropertyKey
{
    return @{};
}

就可以直接存储只含有基础类型的CoreData对象了。


这个例子中还有一个equipments的一对多关系,再实现下面用于转换的方法就可以了
+ (NSDictionary *)relationshipModelClassesByPropertyKey
{
    return @{@"equipments":EquipmentData.class};
}

这里只是介绍了简单的Mantle用法,还有一些进阶的方法需要大家在demo项目中自行理解了,这里就不再多做介绍了


链接: http://pan.baidu.com/s/1c0cWpyg 密码: trba

猜你喜欢

转载自blog.csdn.net/Ginhoor/article/details/41821695