- Introduction to Interface Builder
- Java Code Example
- Objective-C Code Example
- Conclusion
Objective-C Code Example
To accomplish the same task using Interface Builder and Cocoa, I first need to tell XCode to build a new project for me. For this example, I selected a Cocoa application as the template. With the project created, I opened the MainMenu.nib file in Interface Builder.
In Interface Builder, I subclassed NSObject by selecting the classes tab, highlighting NSObject, and then selecting Classes→ Subclass from the menu. In my example, I named the subclass ExampleDelegate. With my new subclass highlighted, I opened the Inspector window and added one action and one outlet. The following figure shows the appropriate sections of the inspector window.
After subclassing NSObject, I instantiated my new subclass by selecting it and then selecting Classes→Instantiate from the menu. This produced a new blue box in the instances tab, as shown in the figure below.
The next step is to place the widgets on the window. Dragging components from the palette, I created a window similar to the one shown in the following figure.
Once the elements are in place on the window, I Control-dragged from the button to my newly instantiated class Selecting fireButton: I hit Connect. I then Control-dragged from my instantiated class to the NSTextField, selected lblDisplay and hit Connect. The final step in Interface Builder is to double-click on ExampleDelegate and select ClassesàCreate Files, which produces the source code for my new class.
Back in XCode, I opened up the newly created ExampleDelegate.m file and added one line of code:
#import "ExampleDelegate.h" @implementation ExampleDelegate - (IBAction)fireButton:(id)sender { [lblDisplay setStringValue:[NSString stringWithFormat:@"Hello World!"]]; } @end
Although this example does not go into the more entertaining and easier-to-manage concepts such as bindings or controllers, it does show how simple GUI construction is with Interface Builder. Note that there was no GUI code generated in this example, and even the small amount of code I did generate was not necessary. I could have just as easily written ExampleDelegate myself and imported it into Interface Builder.