diff --git a/Classes/NSManagedObject+Mappings.m b/Classes/NSManagedObject+Mappings.m index 52adc45..b593a92 100644 --- a/Classes/NSManagedObject+Mappings.m +++ b/Classes/NSManagedObject+Mappings.m @@ -24,6 +24,8 @@ #import "NSManagedObject+ActiveRecord.h" #import "ObjectiveSugar.h" +typedef id (^TransformBlock)(id value, NSManagedObjectContext *context); + @implementation NSManagedObject (Mappings) + (NSString *)keyForRemoteKey:(NSString *)remoteKey inContext:(NSManagedObjectContext *)context { @@ -46,6 +48,11 @@ + (NSString *)keyForRemoteKey:(NSString *)remoteKey inContext:(NSManagedObjectCo } + (id)transformValue:(id)value forRemoteKey:(NSString *)remoteKey inContext:(NSManagedObjectContext *)context { + if ([self cachedMappings][remoteKey][@"transform"]) { + TransformBlock transformer = [self cachedMappings][remoteKey][@"transform"]; + return transformer(value, context); + } + Class class = [self cachedMappings][remoteKey][@"class"]; if (class) return [self objectOrSetOfObjectsFromValue:value ofClass:class inContext:context]; diff --git a/Example/SampleProject.xcodeproj/xcshareddata/xcschemes/SampleProject.xcscheme b/Example/SampleProject.xcodeproj/xcshareddata/xcschemes/SampleProject.xcscheme index 7c18f63..56081db 100644 --- a/Example/SampleProject.xcodeproj/xcshareddata/xcschemes/SampleProject.xcscheme +++ b/Example/SampleProject.xcodeproj/xcshareddata/xcschemes/SampleProject.xcscheme @@ -14,7 +14,7 @@ buildForAnalyzing = "YES"> @@ -28,7 +28,7 @@ buildForAnalyzing = "YES"> diff --git a/Example/SampleProject/Models/Categories/Car+Mappings.m b/Example/SampleProject/Models/Categories/Car+Mappings.m index 098dbae..cde3efd 100644 --- a/Example/SampleProject/Models/Categories/Car+Mappings.m +++ b/Example/SampleProject/Models/Categories/Car+Mappings.m @@ -23,10 +23,13 @@ + (NSDictionary *)mappings { @"class": [InsuranceCompany class] }, @"insurance_company": @{ - @"key": @"insuranceCompany", - @"class": [InsuranceCompany class] - } - + @"key": @"insuranceCompany", + @"transform": ^id(NSDictionary *value, NSManagedObjectContext *context) { + InsuranceCompany * company = [InsuranceCompany findOrCreate:@{@"remoteID": value[@"id"] ?: value[@"remoteID"]} inContext:context]; + [company update:value]; + return company; + } + } }; } diff --git a/Example/SampleProjectTests/MappingsTests.m b/Example/SampleProjectTests/MappingsTests.m index ed6d290..a623d0d 100644 --- a/Example/SampleProjectTests/MappingsTests.m +++ b/Example/SampleProjectTests/MappingsTests.m @@ -73,6 +73,11 @@ Person *bob = [Person findOrCreate:@{ @"first_name": @"Bob" }]; [[bob.firstName should] equal:@"Bob"]; }); + + it(@"uses mappings to transform values", ^{ + Car *car = [Car create:@{ @"hp": @150, @"insurance_company": @{ @"name" : @"Farmers", @"remoteID" : @4567 } }]; + [[car.insuranceCompany.name should] equal:@"Farmers"]; + }); it(@"supports creating a parent object using just ID from the server", ^{ Car *car = [Car create:@{ @"hp": @150, @"insurance_id": @1234 }];