TestsTested | ✓ |
LangLanguage | Obj-CObjective C |
License | MIT |
ReleasedLast Release | Jul 2015 |
NSManagedObject
<-> NSDictionary
(e.g. JSON Model class)
Converting NSManagedObject to NSDictionary (and back again).
pod 'ManagedMappingObject'
1 Setup NSManagedObject class.
You can easily generate using mogenerator.
mogenerator -m ManagedMappingObject.xcdatamodeld -O CoreDataModels \
--base-class ManagedMappingObject \
--template-var arc=true
NSManagedObject
class must be subclass of ManagedMappingObject
.NSManagedObject
class must implement <ManagedMappingProtocol>
.2 Create NSValueTransformer
subclass if need betransformed value.
UnitTransformer
in example case.+ (NSDictionary *)JSONValueTransformerNames
of <ManagedMappingProtocol>
.e.g.)
+ (NSDictionary *)JSONKeyMap {
return @{
UnitAttributes.identifier : @"id",
UnitAttributes.date : @"unix_time",
UnitAttributes.centimeter : @"meter"
};
}
+ (NSDictionary *)JSONValueTransformerNames {
return @{
UnitAttributes.centimeter : NSStringFromClass([MeterToCentimeterTransformer class]),
UnitAttributes.date : NSStringFromClass([UnixTimeToNSDateTransformer class])
};
}
+ (NSString *)entityName {
return [super entityName];
}
3 You can use following method in NSManagedObject, after setup.
// NSDictionary -> NSManagedObject
+ (instancetype)insertNewWithDictionary:(NSDictionary *) dictionary managedObjectContext:(NSManagedObjectContext *) context;
// update NSManagedObject
- (void)updateWithDictionary:(NSDictionary *) dictionary;
// NSManagedObject -> NSDictionary
- (NSDictionary *)dictionaryRepresentation;
NOTE: These methods ignore nil
.
Example
See Example and Tests for details on.
Raw NSDictionary is difficult to deal with, so this example project use JSON Accelerator.
fooJSONModel
class has following useful methods :
- (instancetype)initWithDictionary:(NSDictionary *)dict;
- (NSDictionary *)dictionaryRepresentation;
git checkout -b my-new-feature
git commit -am 'Add some feature'
git push origin my-new-feature
MIT
Thanks @ishkawa