You are not logged in.
NOTE:
Tutorial #5 is very beneficial to begin with. I wrote it after receiving a lot of questions about the other four tutorials. Please consider looking at it first before continuing.
I also did Objective-C and Xcode Essential Training videos that are very beneficial to anyone wanting to learn Objective-C. This will help you tremendously in developing AppleScriptObjC applications.
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.
AppleScriptObjC is a new framework in Mac OS X v10.6 that allows Cocoa applications to be written in AppleScript. Using AppleScriptObjC, your AppleScript code can work with any Cocoa framework, and can function as a first-class citizen in the Cocoa world.
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.
#import <Cocoa/Cocoa.h>
#import <AppleScriptObjC/AppleScriptObjC.h>
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <CoreData/CoreData.h>
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.
Applescript:
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:
-- AppleScript Studio style of targeting a text field
set contents of text field "textField" of window "main" to "some value"
Things start to get a little more hairy once that text field is moved into another view element.
-- AppleScript Studio style of targeting a text field
set contents of text field "textField" of view 1 of view 1 of split view 1 of window "main" to "some value"
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.
Applescript:
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.
Applescript:
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.
Applescript:
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
Applescript:
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.
-- Objective-C
- (void)setTextContainerInset:(NSSize)inset
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.
NSSize
Represents a two-dimensional size.
typedef struct _NSSize {
CGFloat width;
CGFloat height;
} NSSize;
AwakeFromNib Handler
While we are here, let's add some default text to our text field.
Applescript:
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
Applescript:
-- 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
Applescript:
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.
Applescript:
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.
Offline
Thanks so much for this! I've been scratching my head trying to get going with AppleScriptObjC. This is just what I need to get started.
Offline
Thanks for the encouragement Joe!
Offline
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
Offline
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
Offline
Only one blue cube here
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
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!
Offline
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.
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?
Same way. Is that not working for you? Anywhere in your code you call "bog()" you should get a beep.
Offline
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 ;-) ). Are you seeing the button remain highlighted until the handler's script has finished?
Shane Stanley <sstanley@myriad-com.com.au>
www.macosxautomation.com/applescript/apps/
latenightsw.com
Offline
Yes, but it does the same thing in a Cocoa app. I will send you an example.
Offline
By the way, in your final code, am I right in saying you don't need the line:
Applescript:
property aTableView : missing value
Offline
That is correct. I will update the tutorial and the source code. Thanks for catching that!
Offline
@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
---
Last edited by RonaldMHofmann (2009-09-03 09:24:57 pm)
Offline
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
---
Offline
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
---
Offline
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.
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.
Offline
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
---
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.
Applescript:
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
Offline
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 ;-)
I think ASS-OBJC is really thrilling.
Greetings, Ronald
---
Offline
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
Offline
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
Offline
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
Offline
Thank you for the link, anything I can gather will most likely be useful.
I believe with just a small amount of Objective-C understanding, writing applications in AppleScriptObjC will be much easier.
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.
One Last Thing
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.
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!
Last edited by BS0D (2009-09-06 10:16:39 am)
Offline
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 ?
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.
I believe with just a small amount of Objective-C understanding, writing applications in AppleScriptObjC will be much easier.
BSOD wrote:Yes, when you know where to start !
"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
There can be many "blue cubes" in the MainMenu.xib window but since we are dealing with very simple applications there should only be one.
.
.
.
Offline
Yeah, sure it takes time. You know how it is though, pretty much everyone I know who wanted to learn programming also wanted to know it all in a day and be able to code actual applications in no time.
I can't wait for more of your tutorials, they make me a bit more enthusiastic about this whole change in Applescript programming!
(However, Part 2 is waaay too vague for me, after reading 3 times I'm still not getting all of it -- in comparison to part 1 you seem to assume that all your readers have gotten the hang of Objective-C classes etc which is def not the case!)
Offline
you seem to assume that all your readers have gotten the hang of Objective-C classes etc which is def not the case!
I struggle more with writing than I do with coding.
Is there any part that is particularly vague or is the whole thing difficult to understand?
I don't mind re-writing or going into more detail but I would like to work on the areas that
are the most difficult to grasp.
Offline
I struggle more with writing than I do with coding.
I know exactly what you mean, when something is "natural" to you, it's difficult to put yourself back in a position where everything is new, where you're just discovering.
It's nothing personal and I hope I didn't offend you -- sorry for the way I wrote that. Don't get me wrong, you're doing an amazing job here, and needless to say you are a pioneer at this right now.
Is there any part that is particularly vague or is the whole thing difficult to understand?
I don't mind re-writing or going into more detail but I would like to work on the areas that are the most difficult to grasp.
Well for one thing, my C experience dates back to a few years and I've forgotten it all. "Classes", "Parent classes", etc... English not being my native language, are confusing terms as I cannot remember exactly what they are, and what we need them for.
I guess it's nothing in particular, just the whole thing is a little blurry to me.
I guess because the comments seem less clear than explaining exactly what you're about to do, what you need to refer to and THEN showing the code for it, like you did in tutorial 1. Am I making any sense ?
Oh, a few confusing bits to me so far : what's the difference between Cocoa and Objective-C ? Ojb-C is a programming language, so what about Cocoa ? is it a framework or does it have something to do more with the GUI side of programming ? I see both these terms used in documentation, seems like one could be used instead of the other sometimes...
Offline