AppleScriptObjC in Xcode Part 1

Before beginning this tutorial, please read the AppleScriptObjC Release Notes.

Download project source.

I just started playing around with the new AppleScriptObjC framework and I must say this is very cool.
Here is Sal’s description from the release notes.

This takes AppleScript to a whole new level of functionality. In the past our only option to connect to the Cocoa world was through “call method,” which I didn’t care for, and it was confusing and difficult for most to use and understand. It was also limited in the Cocoa methods that were available to it. In addition, AppleScript Studio itself made the verbosity of AppleScript look trivial.

Although the tool we are presented with in Snow Leopard will require AppleScripters to learn some Cocoa, the end result is going to amaze you.

This will be a short tutorial to get you started using AppleScriptObjC in Xcode. We will create a project that has a text field, text view and a button.

To begin with the project will look like this.

Finished App

Here We GO!
Launch Xcode and create a new project. Select “Cocoa - AppleScript Application” and name it whatever you like.

Create a New Project

What You See
This is a full-blown Cocoa application! Awesome! We will be writing our code, for the most part in AppleScript but the application is all Cocoa.

Here is the list a default frameworks that get loaded. There is a tremendous amount of functionality and power here.

AppleScript File
There was one AppleScript file created. Its name is the project name with “AppDelegate” appended to it. Click it to see its code in the editor.

Contents of AppleScript File

The Code
The code is pretty simple but you should notice a few things. The handlers now have and “_” underscore tacked on to the end as well as a parameter. More on this later.

We are going to add some code here to set our parent class. We do this by setting a property called “parent” to the value of the class we want to inherit from. In our case this is NSObject. We add this just below our script opening declaration.


property parent : class "NSObject"

Next we add references to a text field and text view. In AppleScript Studio we would go into Interface Builder, add the text field and text view and give them AppleScript names. At this point we would have referenced them by saying something like:

Things start to get a little more hairy once that text field is moved into another view element.

With AppleScriptObjC this is a thing of the past. We create a reference to the object, in our case a text field, and from then on no matter how many sub views we bury it in, we still have access with a simple call.

Add these references, IBOutlets in Objective-C speak, below the parent declaration. We will hook these up in just a minute.


property textView : missing value
property textField : missing value

Next we will add a button declaration. In Objective-C speak this is an IBAction. The words IBAction and IBOutlet have special meaning in Objective-C for Interface Builder only. When we are in IB these are the properties we will have available to us.

Actions are formed a specific way. There is an underscore at the end of the name and only one parameter.


on setTextViewFromTextField_(sender)
		
end setTextViewFromTextField_

Let’s add some code to take the value we enter into our text field and put it into our text view.


on setTextViewFromTextField_(sender)
	set textFieldValue to textField's stringValue()
	textView's setString_(textFieldValue)
end setTextViewFromTextField_

Once we have hooked up our property “textField” to the actual text field in IB, it will be an NSTextField. When our application runs, it will create an instance of the NSTextField class. The two most common NSTextField methods are “stringValue” and “setStringValue.” In the code above we are sending a message to “textField” (an NSTextField object) and telling it to execute its “stringValue” method. If you look in the documentation under NSTextField you will not find either of these methods. They are inherited from NSControl.

The same goes for the NSTextView. The “setString” method is inherited from NSText. In this method we are sending a message to “textView” (an NSTextView object) and telling it to execute its “setString” method passing it the parameter “textFieldValue.”

If you are wondering why there is not an underscore in “stringValue()” it is because there are no parameters for this method. More on this later.

What the Code looks like so far with a few comments


script PartOneAppDelegate
	-- Inheritance
	property parent : class "NSObject"
	
	-- IBOutlets
	property textView : missing value
	property textField : missing value
	
	-- IBActions (button clicks)
	on setTextViewFromTextField_(sender)
		set textFieldValue to textField's stringValue()
		textView's setString_(textFieldValue)
	end setTextViewFromTextField_
	
	
	##################################################
	# Application
	
	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened 
	end applicationWillFinishLaunching_
	
	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits 
		return my NSTerminateNow
	end applicationShouldTerminate_
	
end script

On to Interface Builder
Double-click on MainMenu.xib as shown below.

MainMenu.xib

If the main window is not already open then double-click it. Drag a text view, text field and button onto the layout and arrange them.

Window Layout

Connecting Objects
Looking in your MainMenu.xib window you will see a blue cube named after your project. Control-drag from the button to this object and release. Select “setTextViewFromTextField_” from the menu that pops up. Now control-drag from the blue cube to the text field and choose “textField.” Do the same for the text view. That’s all there is to it to connecting objects.

Connect Button to Object

Text View
When connecting the text view, be sure to connect to the text view inside the scroll view and not the scroll view.

Connect Text View

Build and Go
We’ve written the code and connected everything in IB so click the Build and Go button. Enter some text into the text field and when you click the button it will appear in the text view.

What Else?
Ok, so that was pretty easy but what else can we do? To start, I like to have a little room around my text inside a text view. Let’s make that happen.

Back in Xcode
We will add an awakeFromNib handler to put our code in. This way the text view is set up as our application is created. NSTextView has a method that we want to use.

The “void” means that the function does not return a value and “(NSSize)” is the required parameter.

You may be asking about now, “What is an “NSSize” and how do I create one?” If you look up this method in the documentation you’ll notice that “NSSize” in the method name is a link to its definition.

NSSize Definition
We see here that NSSize is a struct with two items of type CGFloat. To create this in AppleScript we use a list with two decimal numbers. Pretty easy.

AwakeFromNib Handler
While we are here, let’s add some default text to our text field.


on awakeFromNib()
	textView's setTextContainerInset_({10.0, 10.0})
	textField's setStringValue_("Default text")
end awakeFromNib

Select the Text Field on Application Launch
If you haven’t noticed, each time we launch our application the mouse is in the text view and not in the text field. There are a few things we are going to do to fix this.

  1. Add a property as an outlet to our window
  2. Connect our property in IB using [control + drag] from the “blue cube” to our window.
  3. Use a Window method “makeFirstResponder_()” and give it our text field as a parameter

-- add this below the other property declarations
property aWindow : missing value

-- add this as the last item in the awakeFromNib handler
aWindow's makeFirstResponder_(textField)

Final Code with a few comments


script PartOneAppDelegate
	-- Inheritance
	property parent : class "NSObject"
	
	-- IBOutlets
	-- Interface Builder considers an outlet as any
	-- property with "missing value" as its value
	property textView : missing value
	property textField : missing value
	property aWindow : missing value
	
	-- IBActions (button clicks)
	-- Interface Builder considers an action as any
	-- single parameter method ending with an underscore 
	on setTextViewFromTextField_(sender)
		set textFieldValue to textField's stringValue()
		textView's setString_(textFieldValue)
	end setTextViewFromTextField_
	
	
	##################################################
	# Application
	
	on awakeFromNib()
		textView's setTextContainerInset_({10.0, 10.0})
		textField's setStringValue_("Default text")
		aWindow's makeFirstResponder_(textField)
	end awakeFromNib
	
	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened 
	end applicationWillFinishLaunching_
	
	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits 
		return my NSTerminateNow
	end applicationShouldTerminate_
	
end script

One Last Thing
Go back to Interface Builder, widen your main window and select the text field, text view and button. From the top menu choose “Layout → Embed Objects In → Box.” Adjust your window then build and run. Notice how everything still works. No code adjustment necessary. Go ahead, play around with this. Bury an object inside multiple levels of views and see that no code changes are required. You will get used to this functionality very fast.

Conclusion
Hopefully we have covered enough in this tutorial for you to see the power and potential in AppleScriptObjC. There is a learning curve but I truly believe after a few short months that anyone programming in AppleScriptObjC will not even consider going back to AppleScript Studio.

Want More? View Part 2

Download project source.

Update
If you would like to add to the text inside the text view try implementing something like this.
Notice that textView’s |string|() method has a pipe on each side of the name. This is required
because “string” is an AppleScript keyword.


set theText to textField's stringValue()
set curText to textView's |string|()

tell class "NSString" of current application
	set newText to its stringWithFormat_("%@%@%@", theText, return, curText)
end tell

textView's setString_(newText)

Until next time, happy coding.

The only thing I couldn’t get to work was having the text field as the initial first responder. I added ‘property aWindow : missing value’, put ‘aWindow’s makeFirstResponder_(textField)’ in my awake from nib and control-dragged from the blue cube to the text field and chose ‘aWindow’. Isn’t that everything?

Everything else works great though, thanks :smiley:

One thing I would check is which blue cube did you drag to. When I first wrote the tutorial I did not notice that the class instantiation, blue cube, was already created. If you look at the tutorial now you will see I have removed that section.

If you have two blue cubes named the same thing then remove one of them and make sure all your connections are set up correctly.

hth,

Craig

Only one blue cube here :confused:

Oh well, I can just ctrl-drag from the title bar of the window to the text field and select "initial first responder’ that way, then I don’t have to write any code.

One more thing though, sorry :slight_smile:

In Applescript Studio I used to do stuff like:

on awakeFromNib(theObject)
bog()
end awakeFromNIb

to bog()
beep
end bog

In this example, my app beeps when you open it, but I dont’ have to duplicate code if I want it to beep when you click a button, I can just put ‘bog()’.

I hope it’s clear what I mean by that. How can I do this in AppleScriptObjC?

Joe

PS: AppleScriptObjC apps seem to execute much faster! This is great!

As for the window make sure when you control + drag from the blue cube you are connecting it to the Window and not the View of the Window. Drag to the menu bar.

Same way. Is that not working for you? Anywhere in your code you call “bog()” you should get a beep.

Craig,

Suppose you change your handler to do something more time-consuming, like a delay or a large repeat loop (shock horror, even some work :wink: ). Are you seeing the button remain highlighted until the handler’s script has finished?

Yes, but it does the same thing in a Cocoa app. I will send you an example.

By the way, in your final code, am I right in saying you don’t need the line:

property aTableView : missing value

That is correct. I will update the tutorial and the source code. Thanks for catching that!

@Craig
Hi, I got only one blue cube (it´s a controller?) but it doesn´t react when I control drag from the button.

OK, I think I got it.
My project is named ‘secondTry’.
Unfortunately I copied the code from your example and that is called ‘PartOne’ and in the first line of my project I had PartOneDelegate.
After I changed it to the correct name it worked.

Thanks for this example.

Greetings, Ronald

One mor question please.

the to lines (are they still Handlers?)

on applicationWillFinishLaunching_(aNotification)
      and
on applicationShouldTerminate_(sender)

where are they from? Are they user defined? Looks like since I don´t find them in the Doc.

Greetings, Ronald

some more remarks:

I wondered why
textField’s setStringValue_(“Default text”)

didn´t work inside awakeFromNib()

But it does work when I commet this line out
textView’s setTextContainerInset_({10.0, 10.0})

Debugging is not working, any clues?

Greetings, Ronald

You can find them in the documentation under “NSApplicationDelegate Protocol Reference.”

They are handlers but you do not call them directly, they get called automatically by your application.

Things to try.

  1. Reversing the order. Put setStringValue before textView.
  2. Make sure textView is hooked up inside interface builder. If you are having trouble understanding how to hook things up watch the video on GUI building in Part 2.

Debugging is not working I know. The way I debug is with “log” and “try” statements in my code.
Also, try to focus on getting one thing working at a time and build from there.

Do you have the “Console” open in Xcode when you “Build and Run?” There are error messages there that help in debugging as well.

eg.


log "Setting default value in textField"
textField's setStringValue_("Default text")

log "Setting inset in textView"
try
  textView's setTextContainerInset_({10.0, 10.0})
on error e
  log "Error setting inset: " & e
end try

hth,

Craig Williams

Hi Craig,
thanks a lot for your explanations.
Well I´ve already done some Objective-C this year and are pretty familiar with connecting elements to the controllers.
I´ll give it one more critical look :wink:

I think ASS-OBJC is really thrilling.

Greetings, Ronald

Hi Ronald,

I have noticed that I have to do a “Clean All” more than I would in an Objective-C project.
Maybe doing that will help.

Regards,

Craig

I just read a few topics here today because I was very thrown off by the new Xcode and the changes in Applescript under OS X.6.

I ran into this topic and I will be looking at it thoroughly, and hopefully this will get me started with ApplescriptObjC (which really freaked me out for a second there, going “how the hell am I going to get into that!”).

Thank you Craig, thank you for your work and your contribution.

BS0D

Hi BSOD,

Thank you for the kind words.

I know this is a big change for everyone. I think learning some Objective-C will help in getting the most out of AppleScriptObjC. I mean, just look at the name. Objective-C is part of the name.

I have listed out a few resources for learning Objective-C here.

I believe with just a small amount of Objective-C understanding, writing applications in AppleScriptObjC will be much easier.

Regards,

Craig Williams

Thank you for the link, anything I can gather will most likely be useful.

Yes, when you know where to start !

I’m still very afraid that I’ll be totally incapable to develop any useful, meaningful applications now.
I was thinking of rewriting my first ASS application in ApplescritpObjC but surely it will take some time for me to be able to do that : all the resources I’ve found and looked at so far have confused the hell out of me.

Haven’t looked at part 2 yet, but ALREADY I wonder : how about when there are 3 or 4 textFields on the same window ? How would you make sure you refer to the right one in the code ?
Don’t you have to name them or define them like you would in ASS ?

How would that work ?

I CANNOT WAIT TO LEARN MORE. Despite the difficulty of learning, if not a new programming language, at least its basics, it looks really awesome!

Every object in your window needs a reference to a property in your AppleScript file. Each text field will have its own property. You link the two together in Interface Builder by control dragging from the Application Instance (*blue cube) to the text field and clicking on the corresponding property. Watch the GUI building video from Part 2 for a demonstration on how to do this.

I am currently working on a tutorial to demonstrate how to lookup Objective-C methods in the documentation, understand what you are seeing there and how to convert that to AppleScriptObjC.

“A journey of a thousand miles begins with a single step” - Lao-tzu

I know it is hard learning new languages. It is hard for all of us. You just have to begin. I started by reading Aaron Hillegass’ book. I must have read the first 100 pages at least five times before it started sinking in. I went to the Big Nerd Ranch for a week of training. I spent hours each day going through tutorials, writing code, reading, experimenting, etc. I wrote lots of “throw-away” programs just for the sake of learning.

I did pretty much the same thing to learn FileMaker Pro, AppleScript, HTML, JavaScript, PHP, Ruby, you get the idea. I invest time, money and energy into the process and after a period of time it pays off.

Give yourself time. You can do this!

Regards,

Craig

*blue cube

.
.
.