Binding NSTextField value to NSNumber


(Etan Kissling) #1

Hey there,

I have a model that contains an optional NSNumber.

@objc(Model) final class Model : NSObject {
    dynamic var someNumber: NSNumber?
}

I now bind such en object to an NSObjectController,
and bind the value binding of an NSTextField to the object controller's selection.someNumber key path.

After loading, the number is properly displayed.

(lldb) e/x someNumber!
(__NSCFNumber *) $R0 = 0x0000000000002a57

(lldb) e/d someNumber!.intValue
(Int32) $R1 = 42

However, when I change the entry, the number is replaced by a string.

(lldb) e/x someNumber!
(NSTaggedPointerString *) $R2 = 0x0000000000323425 "42"

(lldb) e/d someNumber!.intValue
(Int32) $R3 = 42

Now, stuff like ==, isEqualToNumber, and compare obviously no longer works.
-[NSTaggedPointerString isEqualToNumber:]: unrecognized selector sent to instance 0x303425

It seems like the NSNumber variable morphed into a NSString.

What's going on here?

Etan

PS: The NSTextField documentation clearly states that NSNumbers are supported to be bound as the value:

value
An NSString or NSNumber that is displayed as the content of the NSTextField.

Availability:
Available in OS X v10.3 and later.


(Jens Alfke) #2

This is a Cocoa question, not a Swift question; a better place to ask is Apple’s cocoa-dev mailing list at http://lists.apple.com, or Apple’s developer forums.

(The quick answer is that NSTextField’s ‘value’ binding is by default an NSString, not an NSNumber. If you want it to be an NSNumber, you’ll need to attach a numeric NSFormatter to the text field. If you have further questions about this, send them to me off-list since this is an off-topic thread.)

—Jens

···

On Jan 6, 2016, at 11:25 AM, Etan Kissling via swift-users <swift-users@swift.org> wrote:

I now bind such en object to an NSObjectController,
and bind the value binding of an NSTextField to the object controller's selection.someNumber key path.