Custom NSValueTransformer in xcode 6 with swift

▼魔方 西西 提交于 2019-12-03 16:48:18

问题


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.

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


回答1:


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.




回答2:


From Xcode release notes:

If you set a Swift subclass of NSValueTransformer as a binding’s value transformer, the XIB or storyboard will contain an invalid reference to the class, and the binding will not work properly at runtime. You can either enter a mangled class name into the Value Transformer field or add the @objc(…) attribute to the NSValueTransformer subclass to solve this problem. (17495784)

From Swift guide:

To make your Swift class accessible and usable back in Objective-C, make it a descendant of an Objective-C class or mark it with the @objc attribute. To specify a particular name for the class to use in Objective-C, mark it with @objc(<#name#>), where <#name#> is the name that your Objective-C code will use to reference the Swift class. For more information on @objc, see Swift Type Compatibility.

Solution:

Declare your class as @objc(myTransformer) class myTransformer: NSValueTransformer and then you can use "myTransformer" as name...



来源:https://stackoverflow.com/questions/25534334/custom-nsvaluetransformer-in-xcode-6-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!