Custom NSValueTransformer in xcode 6 with swift - xcode

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

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...

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.

Related

Xcode 7.1: Property with retain or strong attribute must be of object type

I have this variable in a swift file:
var adbk: ABAddressBook!
Which has always been fine, until Xcode 7.1. Now it complains "Property with retain or strong attribute must be of object type." The error is in the -Swift.h file. Any idea what got changed that would cause this and how to fix it?
This error occurs if Swift class declares some of the AdressBook properties and this class is part of the mixed Swift / ObjC project. Xcode then generate Swift bridging header, where this property becomes (nonatomic, strong), which is applicable to objects only, not structures.
I have encountered similar issue when I needed to pass ABRecordRef from Objective-C class to Swift class: Xcode didn't like my ABRecordRef property in Swift. So I've ended up making that property private, so that it is not exported to the bridging header, and adding new method in Swift class to receive ABRecordRef:
class: PersonDetails {
private var selectedPerson: ABRecorfRef?
func setPerson(person: ABRecordRef) {
selectedPerson = person
}
}
And then you can call
[personDetails setPerson: person];
from Objective-C class.
ABAddressBook is deprecated
#available(iOS, introduced=2.0, deprecated=9.0, message="use CNContactStore")
public typealias ABAddressBookRef = ABAddressBook
so i think you have to use CNContactStore

Adopting NSTextFinderBarContainer protocol in Swift forces variable initialization despite header comment

I have an NSView subclass that implements the NSTextFinderBarContainer protocol. Part of the NSTextFinderBarContainer protocol is implementing
var findBarView: NSView { get set }
However the comment above this property in the original Objective-C header is:
This property is used by NSTextFinder to assign a find bar to a
container. The container may freely modify the view's width, but
should not modify its height. This property is managed by
NSTextFinder. You should not set this property.
Because Swift requires all instance variables to be initialized, how do I handle this situation? It appears Swift requires me to go against what Apple has wrote in the header: you should not set this property as it will be set/managed by the NSTextFinder itself.
If I don't override the NSView initializers I get:
Class 'ExampleContainerView' has no initializers
As expected since findBarView does not have an initial value.
The relevant parts of my Swift code are:
class ExampleContainerView: NSView, NSTextFinderBarContainer {
var findBarView : NSView
...
}
If I override the designated initializer to initialize findBarView as follows (ignoring Apple's comment in the header):
required init?(coder: NSCoder) {
findBarView = NSView(frame: NSRect())
super.init(coder: coder)
}
The app crashes after the NSTextFinder is sent the setFindBarContainer: message
-[NSView _setTextFinder:]: unrecognized selector sent to instance 0x6000001278a0
The object at 0x6000001278a0 is the NSView instance set in the overridden initializer above.
This appears fixed as of Xcode 7.0 beta 6. NSTextFinderBarContainer now declares findBarView as an optional NSView:
public var findBarView: NSView? { get set }
In addition, contentView() also changed to return an optional NSView:
optional public func contentView() -> NSView?
Making the property optional means there is no longer the contradiction of having the API comments say not to set findBarView, while having Swift require that all non-optional properties are initialized in in your initializers.

Use swift global variable (singleton) from Interface Builder

I'm using a global swift variable to create a Singleton like instance. Due to global variables being dispatch_once by default in Swift it works pretty well.
/// LPGlobal.swift
import Foundation
let mySingleton : LPSingleton = LPSingleton()
/// LPSingleton.swift
import Foundation
class LPSingleton {
let myConstant = 10.0
}
Reference from Swift:
/// LPAnySwiftClass.swift
import Foundation
class LPSwiftClass {
init () {
println("my singleton constant: \(mySingleton.myConstant)")
}
}
The Question is: how can I access this LPSingleton class from within Interface Builder?. There is no "Swift class" in the Object library. Do I need to create an Objective-C singleton in order to "act" as a bridge?.
Note: The LPSingleton class is not a subclass of NSObject !!!
Thanks
Luis
Edit: As discussed in the comments, this works only if you subclass NSObject. At the time of this answer there isn't a way to access "pure" Swift classes through IB.
You can drag an "Object" item into IB and assign it a Swift class.
Pick "Object" from the IB palette:
Drag it under your view controller on the left sidebar:
And assign it to your class in the object inspector on the right:

Swift + Xcode 6 beta 3 + Core Data = awakeFromInsert not called?

Need help.
I'm creating new Document-based Core Data Cocoa project.
Add entity named 'Entity' into the core data model. Add 'creationDate' propery into it and set its type as Date. And create NSManagedObject subclass from 'Editor' menu.
Now I add into 'Entity.swift' file this code:
override func awakeFromInsert() {
super.awakeFromInsert()
self.creationDate = NSDate()
println("awakeFromInsert called")
}
Now in my NSPersistentDocument subclass I write such a init() method:
init() {
super.init()
var context = self.managedObjectContext
context.undoManager.disableUndoRegistration()
var entity = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context)
context.processPendingChanges()
context.undoManager.enableUndoRegistration()
println("\(entity)")
}
Everything compiles... BUT awakeFromInsert is never called! The interesting part is that 'entity' object ain't nil! It was created, but not initialized. And if I write this line in init method
entity.creationDate = NSDate()
then creationDate property will be set to a current date as expected.
But that's not all. If I debug execution step-by-step I can see that execution enters 'Entity.swift' file, but starts from the top of the file, then immediately drops and returns back to the NSPersistentDocument subclass file.
Tell me, is it a bug? Because I'm tired to fight with this nonsense. Thanks.
Accidentally I got it work: you have to add #objc(YourSubclass) before subclass declaration. I usually did #objc class MySubclass and turned out it does not work (don't know why).
WORKING:
#objc(YourSubclass)
class YourSubclass : NSManagedObject {
...
NOT WORKING:
#objc class YourSubclass : NSManagedObject {
...

How to initialize a NSWindowController in Swift?

I want to initialize a window controller object from a nib file, quite easy right? But I simply can't get it to work.
According to my previous experience in ObjC, I've written down the following code:
init() {
super.init(windowNibName: "SplitWindowController")
}
And in the app delegate file, I simply init and displays the window:
var myWindowController: MyWindowController = MyWindowController()
myWindowController.showWindow(self)
myWindowController.window.makeKeyAndOrderFront(nil)
But the compiler gives me this error: Must call a designated initializer of the superclass 'NSWindowController'. And according to the Swift version of NSWindowController definition, there are only 3 designated initializers, namely init(), init(window), init(coder). I don't know what to do next. Shall I build a NSCoder from a nib file, which I don't know how to do?
You were almost there. You can indeed override init() as a convenience initialiser in a manner that is equivalent to the Obj-C code you got used to:
import Cocoa
class MyWindowController: NSWindowController {
override convenience init() {
self.init(windowNibName: "<xib name>")
}
}
Note that you are calling init(windowNibName:) on self, because init() being a convenience initialiser, you still inherit all the initialisers from the superclass. From documentation:
Rule 1: A designated initializer must call a designated initializer
from its immediate superclass.
Rule 2: A convenience initializer must call another initializer from
the same class.
Rule 3: A convenience initializer must ultimately call a designated
initializer.
Also, as #weichsel mentioned above, make sure you set the class of the File's Owner to your subclass of NSWindowController (in the example above, that would be MyWindowController) and then connect its window outlet with the window itself.
That being said, I'm not sure why is compiler asking for the override keyword to be added. Though NSWindowController is a subclass of NSResponder, which defines an init(), the following code compiles without issue even though it implements an equivalent inheritance hierarchy:
class A {
init() { }
}
class B: A {
init(Int) {
super.init()
}
convenience init(String) {
self.init(5)
}
}
class C: B {
convenience init() {
self.init("5")
}
}
NSWindowController has 2 designated initializers:
init(window: NSWindow!)
init(coder: NSCoder!)
When creating a subclass, you should invoke the designated initializer of its superclass. Recent versions of Xcode enforce this. Either via built-in language mechanism (Swift) or via NS_DESIGNATED_INITIALIZER macro (Objective-C).
Swift additionally requires that you call the superclasses designated initializer when you override a convenience initializer.
From the "Initialization: Designated Initializers and Convenience Initializers" section of Swift Programming Guide:
If the initializer you are overriding is a convenience initializer,
your override must call another designated initializer from its own
subclass, as per the rules described above in Initializer Chaining.
In your case, you should probably override init(window: NSWindow!) and call super's counterpart from there.

Resources