supermarin / ObjectiveRecord

ActiveRecord-like API for CoreData
MIT License
1.29k stars 194 forks source link

Add support for generic value transformation in mappings #59

Closed kattrali closed 10 years ago

kattrali commented 10 years ago

Right now OR supports value transformation for dates in a common format, or (implicitly) dates in other formats by overriding defaultFormatter in NSManagedObject subclasses.

It would be convenient to support a more generic kind of value transformation. Two ideas:

Option 1 - Formatter Classes

Add a mappings property for formatter that takes an NSFormatter subclass as a value. When a formatter is present, the value for that key is processed through -[FormatterInstance getObjectValue:forString:errorDescription:] before updating the record. Here's an example usage:

+ (NSDictionary *)mappings
{
    return @{
             @"id" : PRIMARY_KEY,
             @"sandwich" : @{
                     @"class": [Sandwich class]
                     @"formatter": [SandwichFormatter class] },
             @"timestamp" : @{
                     @"formatter": [SuperSpecialAPIDateFormatter class] }
             };
}

A caveat would be that we'd presumably need to store any instances of formatters in thread dictionaries, as they may not be threadsafe.

Option 2 - Inline Blocks

Add a transform block to mappings, for inline value formatting. Example:

+ (NSDictionary *)mappings
{
    return @{
             @"id" : PRIMARY_KEY,
             @"sandwich" : @{
                     @"class": [Sandwich class]
                     @"transform": ^(id value) { 
                           return [SandwichFormatter sanitizeParams:value] } },
             @"timestamp" : @{
                     @"transform": ^(id value) { 
                           return [[SuperSpecialAPIDateFormatter sharedFormatter] dateForString:value];  } 
             }
             };
}

Managing thread safety would be up to the user (and therefore NMP), though this way would probably have more code duplication.

supermarin commented 10 years ago

Closing this in favor of #66