Coercing text fields to integers

I have a text entry box on my app’s UI. It is for entering integers only, but as a text field a user can enter anything. I realize I can put a number formatter on it to only accept numbers. But my REAL problem is, in my script how do I always force that variable to be an integer?

So I have a (property) variable “myRows” bound to the UI text field item.
Somehow that variable is really more like an NSString, since it’s bound to the Value binding. Every time I must use this variable in my script I have to say “(myRows as integer)” then do my math function etc.

Also, if I have a checkbox, sometimes it’s read as boolean, sometimes 0/1. It works more reliably if I force it to boolean or force it to integer (0/1). Any reason for that?

Is there a way to sort of always force the variable to be of a certain class? If I use the number formatter, I might always get an NSNumber but still might have to coerce it to integer for Applescript to use it. In Cocoa we can declare a variable as int or NSNumber etc, but only coerce it to something else when we need to. Is there a similar concept in ASOC?


Whenever you use a variable whose value has been set by calling an Objective-C method or via bindings, you have to coerce it to a suitable class to be able to use it in AS. Get used to it.

If it didn’t work this way, you wouldn’t be able to use any instance methods. For example, take this snippet:

set x to current application's NSString's stringWithString_("blah")'s uppercaseString()

The stringWithString_ call returns an NSString object pointer. If that was automatically converted to an AS text object, the call of uppercaseString() would fail.

Thanks Shane. Good to know I wasn’t crazy or missing an important piece of ASOC knowledge.