OCMapper icon indicating copy to clipboard operation
OCMapper copied to clipboard

NSDate Default Mapping

Open abduranjum opened this issue 8 years ago • 3 comments

My understanding from the documentation of OCMapper is that if nothing is set, it should automatically map and reverse map an NSDate. But unfortunately, it doesn't. When it is mapping from object to dictionary, it uses the "description" property of NSDate to get the string. But when it converts from dictionary to object, it is unable to convert it back to NSDate, as it doesn't have a matching dateFormatter. The workaround is to set the defaultDateFormatter to a dateFormatter independent of the locale of the device.

abduranjum avatar Mar 14 '16 10:03 abduranjum

The logic for converting from object to dictionary is a little different. For dictionary to object we can analyze the string to decide what format its using, but for object to dictionary we don't know what the expected format in the dictionary should be. Here is the logic.

https://github.com/aryaxt/OCMapper/blob/master/OCMapper/Source/ObjectMapper.m#L183

It attempts to use a given date formatter for the specific class, if it doesn't exist it attempts to use a default date formatter, otherwise it uses the description.

You either need to give it a default date formatter or a class specific date formatter

aryaxt avatar Mar 14 '16 14:03 aryaxt

That should be stated in the documentation, that it is necessary to set defaultDateFormatter for NSDate to dictionary conversions. And if description was used, it should be handled in the dictionary to NSDate conversion. It's like the mapper cannot read the value it has written itself.

abduranjum avatar Mar 14 '16 14:03 abduranjum

Good point, will add this as enhancement

"Add a new dateformatter to defaultDateFormatters that can handle conversion of NSDate.description"

aryaxt avatar Mar 14 '16 15:03 aryaxt