RKObjectMapping Class Reference
Inherits from | RKMapping : NSObject |
Conforms to | NSCopying |
Declared in | RKObjectMapping.h |
Overview
An RKObjectMapping
object describes a transformation between object represenations using key-value coding and run-time type introspection. The mapping is defined in terms of a source object class and a collection of RKPropertyMapping
objects describing how key paths in the source representation should be transformed into attributes and relationships on the target object. Object mappings are provided to instances of RKMapperOperation
and RKMappingOperation
to perform the transformations they describe.
Object mappings are containers of property mappings that describe the actual key path transformations. There are two types of property mappings:
RKAttributeMapping
: An attribute mapping describes a transformation between a single value from a source key path to a destination key path. The value to be mapped is read from the source object representation usingvalueForKeyPath:
and then set to the destination key path usingsetValueForKeyPath:
. Before the value is set, theRKObjecMappingOperation
performing the mapping performs runtime introspection on the destination property to determine what, if any, type transformation is to be performed. Typical type transformations include reading anNSString
value representation and mapping it to anNSDecimalNumber
destination key path or reading anNSString
and transforming it into anNSDate
value before assigning to the destination.RKRelationshipMapping
: A relationship mapping describes a transformation between a nested child object or objects from a source key path to a destination key path using anotherRKObjectMapping
. The child objects to be mapped are read from the source object representation usingvalueForKeyPath:
, then mapped recursively using the object mapping associated with the relationship mapping, and then finally assigned to the destination key path. Before assignment to the destination key path runtime type introspection is performed to determine if any type transformation is necessary. For relationship mappings, common type transformations include transforming a single object value in anNSArray
or transforming anNSArray
of object values into anNSSet
.
All type transformations available are discussed in detail in the documentation for RKMappingOperation
.
Transforming Representation to Property Keys
Configuring object mappings can become quite repetitive if the keys in your serialized object representations follow a different convention than their local domain counterparts. For example, consider a typical JSON document in the “snake case” format:
{"user": {"first_name": "Blake", "last_name": "Watters", "email_address": "[email protected]"}}
Typically when configuring a mapping for the object represented in this document we would transform the destination properties into the Objective-C idiomatic “llama case” variation. This can produce lengthy, error-prone mapping configurations in which the transformations are specified manually:
RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKUser class]];
[userMapping addAttributeMappingsFromDictionary:@{ @"first_name": @"firstName", @"last_name": @"lastName", @"email_address", @"emailAddress" }];
To combat this repetition, a block can be designated to perform a transformation on source keys to produce corresponding destination keys:
[userMapping setSourceToDestinationKeyTransformationBlock:^NSString *(RKObjectMapping *mapping, NSString *sourceKey) {
// Value transformer compliments of TransformerKit (See https://github.com/mattt/TransformerKit)
return [[NSValueTransformer valueTransformerForName:TKLlamaCaseStringTransformerName] transformedValue:sourceKey];
}];
With the block configured, the original configuration can be changed into a simpler array based invocation:
[userMapping addAttributeMappingsFromArray:@[ @"first_name", @"last_name", @"email_address" ]];
Transformation blocks can be configured on a per-mapping basis via setSourceToDestinationKeyTransformationBlock:
or globally via [RKObjectMapping setDefaultSourceToDestinationKeyTransformationBlock:]
.
Tasks
Creating an Object Mapping
-
+ mappingForClass:
Returns an object mapping for the specified class that is ready for configuration
-
– initWithClass:
Initializes the receiver with a given object class. This is the designated initializer.
-
+ requestMapping
Returns an object mapping with an
objectClass
ofNSMutableDictionary
.
Accessing Property Mappings
-
propertyMappings
The aggregate collection of attribute and relationship mappings within this object mapping.
property -
propertyMappingsBySourceKeyPath
Returns the property mappings of the receiver in a dictionary, where the keys are the source key paths and the values are instances of
propertyRKAttributeMapping
orRKRelationshipMapping
. -
propertyMappingsByDestinationKeyPath
Returns the property mappings of the receiver in a dictionary, where the keys are the destination key paths and the values are instances of
propertyRKAttributeMapping
orRKRelationshipMapping
. -
attributeMappings
The collection of attribute mappings within this object mapping.
property -
relationshipMappings
The collection of relationship mappings within this object mapping.
property -
– mappingForSourceKeyPath:
Returns the property mapping registered with the receiver with the given source key path.
-
– mappingForDestinationKeyPath:
Returns the property mapping registered with the receiver with the given destinationKeyPath key path.
-
– addPropertyMapping:
Adds a property mapping to the receiver.
-
– addPropertyMappingsFromArray:
Adds an array of
RKAttributeMapping
orRKRelationshipMapping
objects to the receiver. -
– removePropertyMapping:
Removes an
RKAttributeMapping
orRKRelationshipMapping
from the receiver. -
– addAttributeMappingsFromDictionary:
Adds attribute mappings from a given dictionary wherein the keys represent the source key path and the values represent the names of the target attributes on the destination object.
-
– addAttributeMappingsFromArray:
Adds attribute mappings to the receiver from a given array.
-
– addRelationshipMappingWithSourceKeyPath:mapping:
Adds a relationship mapping to the receiver with the given source key path and mapping.
Configuring Key Transformation
-
+ setDefaultSourceToDestinationKeyTransformationBlock:
Sets an application-wide default transformation block to be used when attribute or relationship mappings are added to an object mapping by source key path.
-
– setSourceToDestinationKeyTransformationBlock:
Sets a block to executed to transform a source key into a destination key.
Mapping Nested Dictionaries
-
– addAttributeMappingFromKeyOfRepresentationToAttribute:
Adds an attribute mapping from a dynamic nesting key value to an attribute. The mapped attribute name can then be referenced within other attribute mappings to access the nested content.
-
– addAttributeMappingToKeyOfRepresentationFromAttribute:
Adds an attribute mapping to a dynamic nesting key from an attribute. The mapped attribute name can then be referenced wthin other attribute mappings to map content under the nesting key path.
Configuring Mapping Options
-
objectClass
The target class that the receiver describes a mapping for.
property -
setDefaultValueForMissingAttributes
When
propertyYES
, any attributes that have mappings defined but are not present within the source object will be set to nil, clearing any existing value. -
setNilForMissingRelationships
When
propertyYES
, any relationships that have mappings defined but are not present within the source object will be set tonil
, clearing any existing value. -
performKeyValueValidation
When
propertyYES
, key-value validation will be invoked at object mapping time. -
– defaultValueForAttribute:
Returns the default value to be assigned to the specified attribute when it is missing from a mappable payload.
Configuring Date Formatters
-
dateFormatters
An array of
propertyNSFormatter
objects to use when mapping string values intoNSDate
attributes on the targetobjectClass
. Each date formatter will be invoked with the string value being mapped until one of the date formatters does not return nil. -
preferredDateFormatter
The
propertyNSFormatter
object for your application’s preferred date and time configuration. This date formatter will be used when generating string representations of NSDate attributes (i.e. during serialization to URL form encoded or JSON format).
Generating Inverse Mappings
-
– inverseMapping
Generates an inverse mapping for the rules specified within this object mapping.
-
– inverseMappingWithPropertyMappingsPassingTest:
Generates an inverse mapping with all property mappings of the receiver that pass the given test. Each
RKAttributeMapping
andRKRelationshipMapping
added to the receiver is yielded to the block for evaluation. The block is also invoked for any nested relationships that are traversed during the inversion process.
Obtaining Information About the Target Class
-
– classForProperty:
Returns the class of the attribute or relationship property of the target
objectClass
with the given name. -
– classForKeyPath:
Returns the class of the attribute or relationship property of the target
objectClass
at the given key path.
DateAndTimeFormatting Methods
-
+ defaultDateFormatters
Returns the collection of default date formatters that will be used for all object mappings that have not been configured specifically.
-
+ setDefaultDateFormatters:
Sets the collection of default date formatters to the specified array. The array should contain configured instances of NSDateFormatter in the order in which you want them applied during object mapping operations.
-
+ addDefaultDateFormatter:
Adds a date formatter instance to the default collection
-
+ addDefaultDateFormatterForString:inTimeZone:
Convenience method for quickly constructing a date formatter and adding it to the collection of default date formatters. The locale is auto-configured to
en_US_POSIX
. -
+ preferredDateFormatter
Returns the preferred date formatter to use when generating NSString representations from NSDate attributes. This type of transformation occurs when RestKit is mapping local objects into JSON or form encoded serializations that do not have a native time construct.
-
+ setPreferredDateFormatter:
Sets the preferred date formatter to use when generating NSString representations from NSDate attributes. This type of transformation occurs when RestKit is mapping local objects into JSON or form encoded serializations that do not have a native time construct.
Properties
attributeMappings
The collection of attribute mappings within this object mapping.
@property (nonatomic, readonly) NSArray *attributeMappings
Declared In
RKObjectMapping.h
dateFormatters
An array of NSFormatter
objects to use when mapping string values into NSDate
attributes on the target objectClass
. Each date formatter will be invoked with the string value being mapped until one of the date formatters does not return nil.
@property (nonatomic, strong) NSArray *dateFormatters
Discussion
Defaults to the application-wide collection of date formatters configured via [RKObjectMapping setDefaultDateFormatters:]
See Also
[RKObjectMapping defaultDateFormatters]
Declared In
RKObjectMapping.h
objectClass
The target class that the receiver describes a mapping for.
@property (nonatomic, weak, readonly) Class objectClass
Declared In
RKObjectMapping.h
performKeyValueValidation
When YES
, key-value validation will be invoked at object mapping time.
@property (nonatomic, assign) BOOL performKeyValueValidation
Discussion
Default: YES
Declared In
RKObjectMapping.h
preferredDateFormatter
The NSFormatter
object for your application’s preferred date and time configuration. This date formatter will be used when generating string representations of NSDate attributes (i.e. during serialization to URL form encoded or JSON format).
@property (nonatomic, strong) NSFormatter *preferredDateFormatter
Discussion
Defaults to the application-wide preferred date formatter configured via: [RKObjectMapping setPreferredDateFormatter:]
See Also
[RKObjectMapping preferredDateFormatter]
Declared In
RKObjectMapping.h
propertyMappings
The aggregate collection of attribute and relationship mappings within this object mapping.
@property (nonatomic, strong, readonly) NSArray *propertyMappings
Declared In
RKObjectMapping.h
propertyMappingsByDestinationKeyPath
Returns the property mappings of the receiver in a dictionary, where the keys are the destination key paths and the values are instances of RKAttributeMapping
or RKRelationshipMapping
.
@property (nonatomic, readonly) NSDictionary *propertyMappingsByDestinationKeyPath
Return Value
The property mappings of the receiver in a dictionary, where the keys are the destination key paths and the values are instances of RKAttributeMapping
or RKRelationshipMapping
.
Discussion
Warning: Note this method does not return any property mappings with a nil
value for the source key path in the dictionary returned.
Declared In
RKObjectMapping.h
propertyMappingsBySourceKeyPath
Returns the property mappings of the receiver in a dictionary, where the keys are the source key paths and the values are instances of RKAttributeMapping
or RKRelationshipMapping
.
@property (nonatomic, readonly) NSDictionary *propertyMappingsBySourceKeyPath
Return Value
The property mappings of the receiver in a dictionary, where the keys are the source key paths and the values are instances of RKAttributeMapping
or RKRelationshipMapping
.
Discussion
Warning: Note this method does not return any property mappings with a nil
value for the source key path in the dictionary returned.
Declared In
RKObjectMapping.h
relationshipMappings
The collection of relationship mappings within this object mapping.
@property (nonatomic, readonly) NSArray *relationshipMappings
Declared In
RKObjectMapping.h
setDefaultValueForMissingAttributes
When YES
, any attributes that have mappings defined but are not present within the source object will be set to nil, clearing any existing value.
@property (nonatomic, assign, getter=shouldSetDefaultValueForMissingAttributes) BOOL setDefaultValueForMissingAttributes
Declared In
RKObjectMapping.h
Class Methods
addDefaultDateFormatter:
Adds a date formatter instance to the default collection
+ (void)addDefaultDateFormatter:(NSFormatter *)dateFormatter
Parameters
- dateFormatter
An
NSFormatter
object to prepend to the default formatters collection
Declared In
RKObjectMapping.h
addDefaultDateFormatterForString:inTimeZone:
Convenience method for quickly constructing a date formatter and adding it to the collection of default date formatters. The locale is auto-configured to en_US_POSIX
.
+ (void)addDefaultDateFormatterForString:(NSString *)dateFormatString inTimeZone:(NSTimeZone *)nilOrTimeZone
Parameters
- dateFormatString
The dateFormat string to assign to the newly constructed
NSDateFormatter
instance
- nilOrTimeZone
The NSTimeZone object to configure on the
NSDateFormatter
instance. Defaults to UTC time.
Return Value
A new NSDateFormatter
will be prepended to the defaultDateFormatters
with the specified date format and time zone
Declared In
RKObjectMapping.h
defaultDateFormatters
Returns the collection of default date formatters that will be used for all object mappings that have not been configured specifically.
+ (NSArray *)defaultDateFormatters
Return Value
An array of NSFormatter
objects used when mapping strings into NSDate attributes
Discussion
Out of the box, RestKit initializes default date formatters for you in the UTC time zone with the following format strings:
yyyy-MM-dd'T'HH:mm:ss'Z'
MM/dd/yyyy
Declared In
RKObjectMapping.h
mappingForClass:
Returns an object mapping for the specified class that is ready for configuration
+ (instancetype)mappingForClass:(Class)objectClass
Parameters
- objectClass
The class that the mapping targets.
Return Value
A new mapping object.
Declared In
RKObjectMapping.h
preferredDateFormatter
Returns the preferred date formatter to use when generating NSString representations from NSDate attributes. This type of transformation occurs when RestKit is mapping local objects into JSON or form encoded serializations that do not have a native time construct.
+ (NSFormatter *)preferredDateFormatter
Return Value
The preferred NSFormatter object to use when serializing dates into strings
Discussion
Defaults to an instance of the RKISO8601DateFormatter
configured with the UTC time-zone. The format string is equal to “yyyy-MM-DDThh:mm:ssTZD”
For details about the ISO-8601 format, see http://www.w3.org/TR/NOTE-datetime
Declared In
RKObjectMapping.h
requestMapping
Returns an object mapping with an objectClass
of NSMutableDictionary
.
+ (RKObjectMapping *)requestMapping
Return Value
An object mapping with an object class of NSMutableDictionary
.
Discussion
Request mappings are used when configuring mappings that are to be used for transforming local objects into HTTP parameters using the RKObjectParameterization
class.
Declared In
RKObjectMapping.h
setDefaultDateFormatters:
Sets the collection of default date formatters to the specified array. The array should contain configured instances of NSDateFormatter in the order in which you want them applied during object mapping operations.
+ (void)setDefaultDateFormatters:(NSArray *)dateFormatters
Parameters
- dateFormatters
An array of date formatters to replace the existing defaults.
Declared In
RKObjectMapping.h
setDefaultSourceToDestinationKeyTransformationBlock:
Sets an application-wide default transformation block to be used when attribute or relationship mappings are added to an object mapping by source key path.
+ (void)setDefaultSourceToDestinationKeyTransformationBlock:(NSString *( ^ ) ( RKObjectMapping *mapping , NSString *sourceKey ))block
Parameters
- block
The block to be set as the default source to destination key transformer for all object mappings in the application.
Declared In
RKObjectMapping.h
setPreferredDateFormatter:
Sets the preferred date formatter to use when generating NSString representations from NSDate attributes. This type of transformation occurs when RestKit is mapping local objects into JSON or form encoded serializations that do not have a native time construct.
+ (void)setPreferredDateFormatter:(NSFormatter *)dateFormatter
Parameters
- dateFormatter
The NSFormatter object to designate as the new preferred instance
Declared In
RKObjectMapping.h
Instance Methods
addAttributeMappingFromKeyOfRepresentationToAttribute:
Adds an attribute mapping from a dynamic nesting key value to an attribute. The mapped attribute name can then be referenced within other attribute mappings to access the nested content.
- (void)addAttributeMappingFromKeyOfRepresentationToAttribute:(NSString *)attributeName
Discussion
For example, consider the following JSON:
{ "users":
{
"blake": { "id": 1234, "email": "[email protected]" },
"rachit": { "id": 5678", "email": "[email protected]" }
}
}
We can configure our mappings to handle this in the following form:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[User class]];
mapping.forceCollectionMapping = YES; // RestKit cannot infer this is a collection, so we force it
[mapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"firstName"];
[mapping addAttributeMappingsFromDictionary:@{ @"(firstName).id": @"userID", @"(firstName).email": @"email" }];
Declared In
RKObjectMapping.h
addAttributeMappingToKeyOfRepresentationFromAttribute:
Adds an attribute mapping to a dynamic nesting key from an attribute. The mapped attribute name can then be referenced wthin other attribute mappings to map content under the nesting key path.
- (void)addAttributeMappingToKeyOfRepresentationFromAttribute:(NSString *)attributeName
Discussion
For example, consider that we wish to map a local user object with the properties ‘id’, ‘firstName’ and ‘email’:
RKUser *user = [RKUser new];
user.firstName = @"blake";
user.userID = @(1234);
user.email = @"[email protected]";
And we wish to map it into JSON that looks like:
{ "blake": { "id": 1234, "email": "[email protected]" } }
We can configure our request mapping to handle this like so:
RKObjectMapping *mapping = [RKObjectMapping requestMapping];
[mapping addAttributeMappingToKeyOfRepresentationFromAttribute:@"firstName"];
[mapping addAttributeMappingsFromDictionary:@{ @"(firstName).userID": @"id", @"(firstName).email": @"email" }];
Declared In
RKObjectMapping.h
addAttributeMappingsFromArray:
Adds attribute mappings to the receiver from a given array.
- (void)addAttributeMappingsFromArray:(NSArray *)arrayOfAttributeNamesOrMappings
Parameters
- An
array of
RKAttributeMapping
orNSString
values to be added to the receiver’s set of attribute mappings,
Discussion
The array can contain RKAttributeMapping
objects or NSString
values. If an NSString
is given, then a new RKAttributeMapping
object is instantiated with a sourceKeyPath
and destinationKeyPath
equal to the string value.
Declared In
RKObjectMapping.h
addAttributeMappingsFromDictionary:
Adds attribute mappings from a given dictionary wherein the keys represent the source key path and the values represent the names of the target attributes on the destination object.
- (void)addAttributeMappingsFromDictionary:(NSDictionary *)keyPathToAttributeNames
Parameters
- keyPathToAttributeNames
A dictionary keyed by source key to destination attribute name.
Declared In
RKObjectMapping.h
addPropertyMapping:
Adds a property mapping to the receiver.
- (void)addPropertyMapping:(RKPropertyMapping *)propertyMapping
Parameters
- propertyMapping
The property mapping to be added to the object mapping.
Declared In
RKObjectMapping.h
addPropertyMappingsFromArray:
Adds an array of RKAttributeMapping
or RKRelationshipMapping
objects to the receiver.
- (void)addPropertyMappingsFromArray:(NSArray *)arrayOfPropertyMappings
Parameters
- propertyMappings
The array of property mappings to be added to the object mapping.
Declared In
RKObjectMapping.h
addRelationshipMappingWithSourceKeyPath:mapping:
Adds a relationship mapping to the receiver with the given source key path and mapping.
- (void)addRelationshipMappingWithSourceKeyPath:(NSString *)sourceKeyPath mapping:(RKMapping *)mapping
Parameters
- sourceKeyPath
The source key path at which to read the nested representation of the related objects.
- mapping
The object mapping with which to process the related object representation.
Discussion
The destination key path will be the same as the source key path or processed by the source to destination key transformation block, if any is configured.
Declared In
RKObjectMapping.h
classForKeyPath:
Returns the class of the attribute or relationship property of the target objectClass
at the given key path.
- (Class)classForKeyPath:(NSString *)keyPath
Parameters
- propertyName
The name of the property we would like to retrieve the type of.
Return Value
The class of the property at the given key path.
Discussion
Given a key path to a string property, this will return an NSString
, etc.
Declared In
RKObjectMapping.h
classForProperty:
Returns the class of the attribute or relationship property of the target objectClass
with the given name.
- (Class)classForProperty:(NSString *)propertyName
Parameters
- propertyName
The name of the property we would like to retrieve the type of.
Return Value
The class of the property.
Discussion
Given the name of a string property, this will return an NSString
, etc.
Declared In
RKObjectMapping.h
defaultValueForAttribute:
Returns the default value to be assigned to the specified attribute when it is missing from a mappable payload.
- (id)defaultValueForAttribute:(NSString *)attributeName
Discussion
The default implementation returns nil for transient object mappings. On an entity mapping, the default value returned from the Entity definition will be used.
See Also
[RKEntityMapping defaultValueForAttribute:]
Declared In
RKObjectMapping.h
initWithClass:
Initializes the receiver with a given object class. This is the designated initializer.
- (id)initWithClass:(Class)objectClass
Parameters
- objectClass
The class that the mapping targets. Cannot be
nil
.
Return Value
The receiver, initialized with the given class.
Declared In
RKObjectMapping.h
inverseMapping
Generates an inverse mapping for the rules specified within this object mapping.
- (instancetype)inverseMapping
Return Value
A new mapping that will map the inverse of the receiver.
Discussion
This can be used to quickly generate a corresponding serialization mapping from a configured object mapping. The inverse mapping will have the source and destination keyPaths swapped for all attribute and relationship mappings. All mapping configuration and date formatters are copied from the parent to the inverse mapping.
Declared In
RKObjectMapping.h
inverseMappingWithPropertyMappingsPassingTest:
Generates an inverse mapping with all property mappings of the receiver that pass the given test. Each RKAttributeMapping
and RKRelationshipMapping
added to the receiver is yielded to the block for evaluation. The block is also invoked for any nested relationships that are traversed during the inversion process.
- (instancetype)inverseMappingWithPropertyMappingsPassingTest:(BOOL ( ^ ) ( RKPropertyMapping *propertyMapping ))predicate
Parameters
- predicate
A block object to be invoked for each
RKPropertyMapping
that is considered for inversion. The block has a Boolean return value and accepts a single argument: the property mapping that is being evaluated for inversion.
Return Value
A new mapping that will map the inverse of the receiver.
See Also
Declared In
RKObjectMapping.h
mappingForDestinationKeyPath:
Returns the property mapping registered with the receiver with the given destinationKeyPath key path.
- (id)mappingForDestinationKeyPath:(NSString *)destinationKeyPath
Parameters
- destinationKeyPath
The key path to retrieve.
Declared In
RKObjectMapping.h
mappingForSourceKeyPath:
Returns the property mapping registered with the receiver with the given source key path.
- (id)mappingForSourceKeyPath:(NSString *)sourceKeyPath
Parameters
- sourceKeyPath
The key path to retrieve.
Declared In
RKObjectMapping.h
removePropertyMapping:
Removes an RKAttributeMapping
or RKRelationshipMapping
from the receiver.
- (void)removePropertyMapping:(RKPropertyMapping *)propertyMapping
Parameters
- propertyMapping
The attribute or relationship mapping to remove.
Declared In
RKObjectMapping.h
setSourceToDestinationKeyTransformationBlock:
Sets a block to executed to transform a source key into a destination key.
- (void)setSourceToDestinationKeyTransformationBlock:(NSString *( ^ ) ( RKObjectMapping *mapping , NSString *sourceKey ))block
Parameters
- block
The block to execute when the receiver needs to transform a source key into a destination key. The block has a string return value specifying the destination key and accepts a single string argument: the source key that is to be transformed.
Discussion
The transformation block set with this method is used whenever an attribute or relationship mapping is added to the receiver via a method that accepts a string value for the source key. The block will be executed with the source key as the only argument and the value returned will be taken as the corresponding destination key. Methods on the RKObjectMapping
class that will trigger the execution of the block configured via this method include:
* addAttributeMappingsFromArray:
– Each string element contained in the given array is interpretted as a source key path and will be evaluated with the block to obtain a corresponding destination key path.
* addRelationshipMappingWithSourceKeyPath:mapping:
– The source key path will be evaluated with the block to obtain a corresponding destination key path.
Warning: Please note that the block given accepts a key as opposed to a key path. When a key path is given to a method supporting key transformation it will be decomposed into its key components by splitting the key path at the ‘.’ (period) character, then each key will be evaluated using the transformation block and the results will be joined together into a new key path with the period character delimiter.
Declared In
RKObjectMapping.h