aryaxt / OCMapper

Objective-C library to easily map NSDictionary to model objects, works perfectly with Alamofire. ObjectMapper works similar to GSON
MIT License
347 stars 45 forks source link

NSDate Default Mapping #44

Open abduranjum opened 8 years ago

abduranjum commented 8 years ago

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.

aryaxt commented 8 years ago

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

abduranjum commented 8 years ago

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.

aryaxt commented 8 years ago

Good point, will add this as enhancement

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