How do I setup cocoa bindings for properties that are of optional datatype?
I have an NSTableView that displays data from NSArrayController via key bindings, which in turn is managing objects for an array of [Properties] which are defined as:
class Property: NSObject {
var distance: CLLocationDistance
var ETA: TimeInterval?
var coordinates: CLLocationCoordinate2D
// other properties and methods here
}
in MainViewController I define
var properties: [Property] = []
@IBOutlet var arrayController: NSArrayController!
where arrayController is bound to properties
array, NSTableView
is bound to Array Controller (Controller Key = arrangedObjects
) and then individual TableViewCells
bound to various properties of Table Cell View (model key path = objectValue.distance
, etc)
The code compiles without any issues, but at runtime it crashes when it tries to load the table. The issue is with the ETA column since properties.ETA
is an optional. What is the proper way of dealing with this issue? Thank you
You can't, at least not directly.
Cocoa Bindings work through the Objective-C runtime, and ObjC has no way to represent Swift Optionals that aren't of object (aka class aka reference) type. (That is, you can access an NSWindow?
from ObjC, or even an AnyObject?
, but not an Int?
or a CGRect?
or a TimeInterval?
.)
Your best bet here is probably to fall back to doing things the way you would in ObjC — make ETA
a non-optional TimeInterval
, and use some sentinel value (negative something-huge?) to represent cases where an ETA is not set. You can use value transformers to make sure such cases get represented appropriately in your UI.
Alternately, you could keep the optional property for use in Swift, and expose a second, computed property of non-optional type for use in bindings.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments