قالب وردپرس درنا توس
Home / IOS Development / ValueTransformer – NSHipster

ValueTransformer – NSHipster



Of all the basic classes,
Value Transformer is perhaps the one who went the worst
in the switch from macOS to iOS.

Why? Here are two reasons:

First,
Value Transformer was used primarily in AppKit with cocoa bonds.
There they could automatically convert values ​​from one property to another,
like to ignore a Boolean or check if a value was null ,
without the need for intermediate adhesive code.
IOS, of course, has no bindings.

The second reason has less to do with iOS than the objective-C drive time itself.
With the introduction of blocks,
it became much easier to pass behavior between objects ̵

1;
significantly easier than, say Value Transformer or NSInvocation .
So even though iOS would get bindings tomorrow,
it's unclear about Value Transformer
would play an important role this time.

But you know what?
Value Transformer may just be ripe for a comeback.
With some re-tooling and some recontextualization,
This blast from the past can be the next major in your application.


Value Transformer is an abstract class that turns one value into another.
A transformation indicates which types of input values ​​can be handled
and if it supports reversible transformations.

A typical implementation looks like this:

  class    ClassNameTransformer :    ValueTransformer    {
      override    class    func    transformedValueClass  ( )    ->    AnyClass    {. 
          return [19659000] NSString    self 
    } 

      ride    class    FUNC    allowsReverseTransformation  ()    ->    Boolean    { 
          return    false 
    } 

      ride    FUNC    transformedValue  (  _    value :    Any )?    -> [19659000] Any     {
          guard    la    type    =    value    as? [19659000] AnyClass    Otherwise       Return    nil  }    Return    NSStringFromClass [19659010] (  [19659010] 
    }   } 

  @interface    ClassNameTransformer :    NSValueTransformer    {} 
  @end 

  #pragma mark -

  @implementation    ClassNameTransformer 
  +    (  Class )   transformedValueClass    {
    return    [  NSString    class [19659010]]; 
] 

  +    (  BOOL )   allows ReverseTransformation    {
      return    NO ;  ]   [ ]   id )   transformedValue :  (  id )   value    {
      ]        value    ==    nil )       nil  :    NSStringFromClass  [  value    class ]); 
} 
  @end 

Value Transformer is rarely initialized directly.
Instead, it follows a pattern known to fans of
NSPersistent Store or NSURLProtocol ,
Where a class is registered and instances are created from a leader –
except in this case, you register a named example to act as a singleton:

  extension    ClassNameTransformer    {
      static    la    name    = 19659009] NSValueTransformerName     rawValue :    "ClassNameTransformer" ) 
} 

  // Enter Value Transformers 
  ValueTransformer . 
       ]  ] 
                                       // Get Value Transformer  ]  (), 
                                       forName :    ClassNameTransformer .   name ] la    valueTransformer    =    valueTransformer  (  forName .    ClassNameTransformer    name ) 

  ] NSValueTransformerName    art    ClassNameTransformerName    =    @ "ClassNameTransformer" ; 
     ] Set the Value Transformer 
 [  N SValueTransformer    setValueTransformer : [[  ClassNameTransformer    lloc ]    init ]    forName :   ClassNameTransformerName ]; [19659142] // Get the value transformer 
  NSValueTransformer    *   valueTransformer    =    [  NSValueTransformer    valueTransformerForName :   ClassNameTransformerName ]; 

] A common pattern is to record the singleton instance
i + initialization method for the sub-class of the transformer
so it can be used without additional setup.

Now you probably understand Value Transformer s fatal error:
It is very annoying to set up!
Create a class,
implement a handful of simple methods,
define a constant,
and register it in a + initialization method ? No thanks.

In this age of blocks,
we want – no, demand
One way to declare functionality in one (albeit giant) line of code.

Nothing a little metaprogramming can not fix.
See:

  la    TKCapitalizedStringTransformerName    = 
      NSValueTransformerName  (  rawValue :    "TKC ​​CapitalizedStringTransformerName" ). 

  ValueTransformer  [19659145] registerValueTransformerWithName  (  TKCitalizedStringTransformerName  
     transformedValueClass .    NSString    ]       item    in 
          cover    la    string    =    item    as?    string          return    nil  }    return    string    modified 
} 

  NSValueTransformerName    art    TKCapitalizedStringTransformerName    =    @ "TKCitalizedStringTransformerName" ;   ]   NSValueTransformer    registerValueTransformerWithName :   TKCapitalizedS tringTransformerName 
             transformedValueClass : [  NSString    class ] 
  return TransformedValueWithBlock : ^   id  (  id    value )          [  value    capitalizedString ]; 
}]; 


Now with a new look,
We can start to get a better understanding of
how to take advantage of Value Transformer :

Make Business Logic More Functional

Value Transformers Articles are a great way to represent
an ordered chain of permanent transformations.
For example, an app interface with an older system
can change user input through a series of string transformations
(trim whitespace, remove diacritics, and then capitalize letters)
before sending it to the main frame.

Think forward and backward

Unlike blocks, value transformers have the term reversibility,
which enables some interesting usage cases.

Say you wanted to map keys from a REST API representation to a model.
You can create a reversible transform that converted snake_case to llama Case upon initialization,
and llama Case to snake_case when serializing back to the server.

Configure functionality

Another advantage than the blocks is that
Value Transformers subclasses can reveal new features
which can be used to configure behavior in a particular way.
Access to properties also provides a clean way to cache or remember the results
and do the necessary bookkeeping along the way.

Transform Core Data Stack

Let's forget,
Value Transformer can be used with Core Data
to encode and decode composite data types from blob fields.
It seems to have fallen out of fashion over the years,
but serializes simple collections this way
can be a winning strategy for difficult data.
(Just do not use these steps to serialize images or other binary data;
use external storage instead)


Value Transformer ,
far from a west of AppKit,
remains the Foundation's purest connection to functional programming:
input goes in, output comes out.

Although it is true that Objective-C is blocking
and all the advanced language features in Swift
are superior examples of the functional programming paradigm.
Value Transformer has a special place in cocoa history and Xcode tools.
Therefore, object orientation is transformed
from an embarrassing responsibility to its greatest asset.

And although it has not grown very well alone,
a little modernization restores Value Transformer
to the highest esteem of NSHipsterdom:
a solution that we did not know we needed
but was there all the time.


Source link