xcodeswiftnsvaluetransformer

Custom NSValueTransformer in xcode 6 with swift


Did anyone successfully implement a custom NSValueTransformer in xcode 6 beta with swift?

I have the following swift class:

import Foundation

class myTransformer: NSValueTransformer {

  let amount = 100

  override class func transformedValueClass() -> AnyClass!
  {
    return NSNumber.self
  }

  override func transformedValue(value: AnyObject!) -> AnyObject! {
    return value.integerValue + amount
  }
}

So all this transformer should do is, adding 100 to a given value in the gui.

As you can see, the transformer class appears now in the Value Transformer drop down in IB.

enter image description here

But if I choose this transformer the application crashes with:

2014-08-27 20:12:17.686 cdTest[44134:303] 
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
reason: 'Cannot find value transformer with name newTransformer'

Is it right to register this transformer in the AppDelegate with

override class func initialize() {
  let newTransformer = myTransformer()
}

Does anyone know how this whole stuff should work?

kind regards! martin


Solution

  • After you initialise newTransformer you should also include the line:

    NSValueTransformer.setValueTransformer(newTransformer, forName: "myTransformer")
    

    Then in your Interface Builder you should use myTransformer instead of newTransformer under the Value Transformer dropdown.