Get all Mac OS X Tips, Tricks, Tutorials, Hacks, Support, Downloads, Updates...right in to your Mac OS X Mountain Lion, Lion, Snow Leopard, Leopard or Tiger Dashboard !
Learn How To using Finder, Preview, iChat, iCal, Mail, Safari, Address Book, Expose, Dock, Dashboard, Spotlight, Keyboard Shortcuts...or Customizing Your Mac !
↓ Download
Get the latest iPhone, iPad and iPod Touch Applications, iOS Tips, Tutorials, Documentation, and Downloads - Become an iOS Developer and start developing, testing, and distributing your iOS Application for iPhone, iPad and iPod Touch today.
Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. Show all posts
Moving from Xcode 3 to Xcode 4
The majority of changes that will affect you for Xcode 4 are related to a redesigned user interface. This post offers a general overview of these differences, including hidden panels and integrated Interface Builder.
Overall Interface Redesign
Perhaps the most obvious change is that everything is now unified into a single-window interface.
When you first open a project in Xcode 4 (or create a new one), you’ll notice a lack of items in the lefthand portion (which under Xcode 3 would be the Groups & Files list). For the TextApp project from the first chapter of the book, you’ll find only a single item listed, with an Xcode project icon:
Expand this to see the files within it, and click a file to open it in the editor:
Because Xcode 4 is designed primarily so that everything occurs within a single window (it is still possible to double-click a file to open it in a separate window), many features are “hidden” behind panels and navigator controls.
The left portion of the main window contains Navigators, each of which is used to navigate through different aspects of a project—use the little icon buttons to choose which one. Since you’ll find yourself swapping between navigators fairly frequently, it’s worth pointing out that the icons correspond to the options in the View > Navigators menu, so each has a prominent keyboard shortcut.
If you’re relatively new to coding, or even just to Xcode, it’s easy to become confused as to why you’re not seeing what you think you should be seeing in this navigator pane. To see the list of groups and files, you need the Project Navigator (Cmd-1).
Debugger Console
The Debugger Console (a separate window under Xcode 3) has also been moved into the main interface, and the default keyboard shortcut has changed. You’ll need to use the segmented control labelled View in the main toolbar of the Xcode window to display the “bottom bar.”
This lower panel is known as the Debug Area in Xcode 4, and can also be hidden/shown from the View menu (Shift-Cmd-Y). The Debug Area has several purposes; it’s also used instead of another, separate Debugger window in Xcode 3. Depending on which you need (it’s the Console area on the right for this book), you can choose whether to show both panels or just one using the segmented control that appears in the lower panel of the window:
The default behavior in Xcode 4 is to hide the debug area each time you run an application. If you wish, you can change this—choose Xcode > Preferences… (Cmd-,) and select the Behaviors tab, then set what happens when a Run starts to Show the Debug Area automatically each time:
Note that if you’re particularly attached to any default Xcode 3 keyboard shortcuts, it’s possible to change the Xcode 4 shortcuts using the Key Bindings tab in the Preferences window.
Separate Windows
If you don’t like having everything arranged on the one window, Xcode 4 can open as many extra windows as you like. Double-clicking any file, for example, will open that file in a new window. Working with multiple windows can get confusing, though, particularly when it comes to closing the project. Skip this section if you’re still relatively new to Xcode in any version.
Once you have a new window open, you decide how much you want it to display. If you particularly want a separate debugger console window, for example, choose File > New > New Window (Shift-Cmd-T). By default, a new window opened in this way will display the same information as the previous front-most window. If this is the first new window you’ve opened for a project, you’ll effectively get two identical Xcode project windows. Use the new window’s main toolbar to turn off the left and right bars, and display the bottom bar, then drag the bottom bar up to fill the window:
Once you’ve done that, you can hide the main toolbar itself by clicking the button in the top right of the window’s title bar:
Xcode 4 will remember the window locations and layout when you close the project, but make sure you use File > Close Project to do so (by default this doesn’t have a keyboard shortcut, but you can add one in the Preferences window—in the Key Bindings panel, the command is listed as Close Workspace).
If you instead try to close the project by closing what looks to you like the main project window, the project will still be open, but with only the shrunk console window on display. If you then close this window as well (at which point Xcode will close the project because that’s the last open window), then all you’ll see when you next open the project will be the console window. The first time this happened to me, I had a minor panic trying to figure out how to get back to my original window. If this happens to you, just calmly re-display the main toolbar, and open the left, Navigators area. Hide the bottom bar, and you’ll be back to a normal “project window.”
Execution Controls
To match the iTunes-like single-window interface, the Xcode 3 Build and Run/Stop buttons have been replaced in Xcode 4 with simple Run and Stop buttons in the main toolbar:

The default shortcuts for Building (Cmd-B), Running (Cmd-R), and Cleaning (Shift-Cmd-K) remain the same under Xcode 4—the menu commands are found under the Product menu.
In the middle of the toolbar is a status area, again much like iTunes, to indicate what’s going on. If a Build fails with errors or generates warnings, these are indicated in this area.
Notice also that if errors or warnings are generated, these are displayed in the Issue Navigator pane on the left, which will appear automatically if issues are found. This Issue Navigator (Cmd-4) replaces the separate Build Results window under Xcode 3. As before, errors and warnings are displayed as overlays on top of the relevant code:
And, as mentioned earlier, when you want to get back to the list of files in the project you’ll need to switch to the Project Navigator pane (Cmd-1).
Editors
Xcode 4 has a variety of editor “modes,” including an Assistant editor. Any time you open a file when using the Assistant, Xcode 4 will also display what it thinks is the most closely-related file (such as the class interface header file for a class implementation).
Switch to the Assistant by using the Editor segmented control in the main toolbar, or choose View > Editor > Assistant (Opt-Cmd-Return):
Health Warning: Use of Xcode 4 may cause extreme desire for a larger monitor/display
If you prefer viewing just one file at a time, you can use the Related Files popup menu to jump between counterparts, and even superclasses, protocol definitions, etc:
Note that the default shortcut to display the counterpart file (i.e., jump from an implementation file to an interface file), has changed from Opt-Cmd-UpArrow to Ctrl-Cmd-UpArrow. Take a look at the list of Jump commands in the Navigate menu for a full list of helpful shortcuts.
The third editor, the Version editor, is used for projects under a source code Version Control System, e.g. Git or Subversion. Versioning isn’t something covered in the book, but it’s a great addition to Xcode for when you start using a system like Git.
Integrated Interface Builder
Interface Builder used to be a separate application, which would communicate behind the scenes with the Xcode 3 environment to make sure relevant code changes were represented in the interface. There were a few gotchas with this, including the need to save .xib or .nib files in Interface Builder before Building and Running in Xcode.
Under Xcode 4, the entire interface-editing environment has been integrated into the Xcode application itself.
When you click a .xib file, it will open in the editor:
The left hand side of this editor pane contains the icons representing the objects within the .xib file. If you click the window icon, the window will appear in the pane:
The blue box surrounding the window in the graph paper area includes a Close button to hide the window from the editor; if you need to show lots of objects in the editor pane, you can drag the blue box containers to rearrange items.
Inspectors
The object inspectors are no longer found under separate panels in Xcode 4; instead, you’ll need to use the main toolbar View segmented control to display the “right bar,” or Utilities area:
The top half of this Utilities area contains Inspector panels. Just like Navigators on the left of the window, you use the little icon buttons to swap between the different inspectors, which also have corresponding menu items and keyboard shortcuts:

Libraries
The lower half of the Utilities area is used for Libraries. Again, use the little icon buttons to switch between them (or use the menu options shown above). For interface editing, you’ll need the Object Library (Ctrl-Opt-Cmd-3):

Making Connections
IBOutlet and IBAction connections are made in the same way as they were in the standalone Interface Builder.
If you’re making a connection from one of several objects in the left-hand column of the Interface Editing panel, hover over any icon to show its class name:

Right-click (or Ctrl-click) to show the available connections, and click-drag out from the circle to make the connection:
Under Xcode 4, there’s also another connection option available if you use the Assistant Editor.
The Assistant Editor will display the class interface that it thinks is most closely related to the objects in a .xib file; for the TextApp application, this will likely be the TextAppAppDelegate.h file. Given that the connections you’ll need to make in the book are initially for the NotifyingClass object, you’ll need to use the Assistant’s file dropdown to choose one of the other related files, NotifyingClass.h:
Once you’ve done this, Xcode 4 allows you to make connections directly to the IBAction and IBOutlet entries in the code file:

You’ll need to hover over the code until the words “Connect Action” or “Connect Outlet” appear; if you hover in an empty area, or between lines, Xcode 4 will insert an action or outlet automatically at the code location where you release the mouse button.
If you hover in one place for two long, Xcode 4 may “drill down” into the code, and show you superclass interfaces, etc. If this happens, either use the file dropdown mentioned above, or the back/forward buttons at the top left of the assistant’s code file panel:

Project Template Changes
The templates seem to change with every minor revision of Xcode. For Xcode 4 onwards, you’ll find the organization of the project is slightly different from that shown in the book for Xcode 3. You should find that the files still have the same names, but the Classes group now has the name of your application, and the various resources and other sources are now found either inside this group or inside its Supporting Files group.
The code that’s included in the project templates has also changed a little. You’ll find that any provided init method, which used to look like this:
- (id)init
{
if (self = [super init]) {
// Initialization code here.
}
return self;
}
now looks like this:
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
One change in Xcode 4 that may cause confusion is that you’ll now get a warning if you use the first style—you’ll now get a warning any time you use an assignment inside a conditional if() statement. If you are particularly attached to using this style, you’ll need to add an additional set of parentheses to silence the warning:
- (id)init
{
if ((self = [super init])) {
// Initialization code here.
}
return self;
}
Overall Interface Redesign
Perhaps the most obvious change is that everything is now unified into a single-window interface.
When you first open a project in Xcode 4 (or create a new one), you’ll notice a lack of items in the lefthand portion (which under Xcode 3 would be the Groups & Files list). For the TextApp project from the first chapter of the book, you’ll find only a single item listed, with an Xcode project icon:


The left portion of the main window contains Navigators, each of which is used to navigate through different aspects of a project—use the little icon buttons to choose which one. Since you’ll find yourself swapping between navigators fairly frequently, it’s worth pointing out that the icons correspond to the options in the View > Navigators menu, so each has a prominent keyboard shortcut.

Debugger Console
The Debugger Console (a separate window under Xcode 3) has also been moved into the main interface, and the default keyboard shortcut has changed. You’ll need to use the segmented control labelled View in the main toolbar of the Xcode window to display the “bottom bar.”
This lower panel is known as the Debug Area in Xcode 4, and can also be hidden/shown from the View menu (Shift-Cmd-Y). The Debug Area has several purposes; it’s also used instead of another, separate Debugger window in Xcode 3. Depending on which you need (it’s the Console area on the right for this book), you can choose whether to show both panels or just one using the segmented control that appears in the lower panel of the window:


Separate Windows
If you don’t like having everything arranged on the one window, Xcode 4 can open as many extra windows as you like. Double-clicking any file, for example, will open that file in a new window. Working with multiple windows can get confusing, though, particularly when it comes to closing the project. Skip this section if you’re still relatively new to Xcode in any version.
Once you have a new window open, you decide how much you want it to display. If you particularly want a separate debugger console window, for example, choose File > New > New Window (Shift-Cmd-T). By default, a new window opened in this way will display the same information as the previous front-most window. If this is the first new window you’ve opened for a project, you’ll effectively get two identical Xcode project windows. Use the new window’s main toolbar to turn off the left and right bars, and display the bottom bar, then drag the bottom bar up to fill the window:


If you instead try to close the project by closing what looks to you like the main project window, the project will still be open, but with only the shrunk console window on display. If you then close this window as well (at which point Xcode will close the project because that’s the last open window), then all you’ll see when you next open the project will be the console window. The first time this happened to me, I had a minor panic trying to figure out how to get back to my original window. If this happens to you, just calmly re-display the main toolbar, and open the left, Navigators area. Hide the bottom bar, and you’ll be back to a normal “project window.”
Execution Controls
To match the iTunes-like single-window interface, the Xcode 3 Build and Run/Stop buttons have been replaced in Xcode 4 with simple Run and Stop buttons in the main toolbar:

The default shortcuts for Building (Cmd-B), Running (Cmd-R), and Cleaning (Shift-Cmd-K) remain the same under Xcode 4—the menu commands are found under the Product menu.
In the middle of the toolbar is a status area, again much like iTunes, to indicate what’s going on. If a Build fails with errors or generates warnings, these are indicated in this area.
Notice also that if errors or warnings are generated, these are displayed in the Issue Navigator pane on the left, which will appear automatically if issues are found. This Issue Navigator (Cmd-4) replaces the separate Build Results window under Xcode 3. As before, errors and warnings are displayed as overlays on top of the relevant code:

Editors
Xcode 4 has a variety of editor “modes,” including an Assistant editor. Any time you open a file when using the Assistant, Xcode 4 will also display what it thinks is the most closely-related file (such as the class interface header file for a class implementation).
Switch to the Assistant by using the Editor segmented control in the main toolbar, or choose View > Editor > Assistant (Opt-Cmd-Return):

If you prefer viewing just one file at a time, you can use the Related Files popup menu to jump between counterparts, and even superclasses, protocol definitions, etc:

The third editor, the Version editor, is used for projects under a source code Version Control System, e.g. Git or Subversion. Versioning isn’t something covered in the book, but it’s a great addition to Xcode for when you start using a system like Git.
Integrated Interface Builder
Interface Builder used to be a separate application, which would communicate behind the scenes with the Xcode 3 environment to make sure relevant code changes were represented in the interface. There were a few gotchas with this, including the need to save .xib or .nib files in Interface Builder before Building and Running in Xcode.
Under Xcode 4, the entire interface-editing environment has been integrated into the Xcode application itself.
When you click a .xib file, it will open in the editor:


Inspectors
The object inspectors are no longer found under separate panels in Xcode 4; instead, you’ll need to use the main toolbar View segmented control to display the “right bar,” or Utilities area:


Libraries
The lower half of the Utilities area is used for Libraries. Again, use the little icon buttons to switch between them (or use the menu options shown above). For interface editing, you’ll need the Object Library (Ctrl-Opt-Cmd-3):

Making Connections
IBOutlet and IBAction connections are made in the same way as they were in the standalone Interface Builder.
If you’re making a connection from one of several objects in the left-hand column of the Interface Editing panel, hover over any icon to show its class name:

Right-click (or Ctrl-click) to show the available connections, and click-drag out from the circle to make the connection:

The Assistant Editor will display the class interface that it thinks is most closely related to the objects in a .xib file; for the TextApp application, this will likely be the TextAppAppDelegate.h file. Given that the connections you’ll need to make in the book are initially for the NotifyingClass object, you’ll need to use the Assistant’s file dropdown to choose one of the other related files, NotifyingClass.h:


You’ll need to hover over the code until the words “Connect Action” or “Connect Outlet” appear; if you hover in an empty area, or between lines, Xcode 4 will insert an action or outlet automatically at the code location where you release the mouse button.
If you hover in one place for two long, Xcode 4 may “drill down” into the code, and show you superclass interfaces, etc. If this happens, either use the file dropdown mentioned above, or the back/forward buttons at the top left of the assistant’s code file panel:

Project Template Changes
The templates seem to change with every minor revision of Xcode. For Xcode 4 onwards, you’ll find the organization of the project is slightly different from that shown in the book for Xcode 3. You should find that the files still have the same names, but the Classes group now has the name of your application, and the various resources and other sources are now found either inside this group or inside its Supporting Files group.
The code that’s included in the project templates has also changed a little. You’ll find that any provided init method, which used to look like this:
- (id)init
{
if (self = [super init]) {
// Initialization code here.
}
return self;
}
now looks like this:
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
One change in Xcode 4 that may cause confusion is that you’ll now get a warning if you use the first style—you’ll now get a warning any time you use an assignment inside a conditional if() statement. If you are particularly attached to using this style, you’ll need to add an additional set of parentheses to silence the warning:
- (id)init
{
if ((self = [super init])) {
// Initialization code here.
}
return self;
}
Creating an Interactive iPhone App
Creating the New Project
The purpose of the application we are going to create is to perform unit conversions from Fahrenheit to Centigrade. Obviously the first step is to create a new Xcode project to contain our application.
Start Xcode and on the Welcome screen select Create a new Xcode project. On the template screen choose the Application option located under iOS in the left hand panel and select View-based Application. Click Next, name the product UnitConverter, enter your company identifier and make sure that the Product menu is set to iPhone. On the final screen, choose a location in which to store the project files and click on Create to proceed to the main Xcode project window.
Creating the User Interface
Before we begin developing the logic for our interactive application we are going to start by designing the user interface. When we created the new project, Xcode generated an Interface Builder NIB file for us and named it UnitConverterViewController.xib. It is within this file that we will create our user interface, so select this file from the project navigator in the left hand panel to load it into Interface Builder. Once Interface Builder has loaded the file select the far right of the three View buttons in the Xcode toolbar to display the right hand panel. In the lower panel, select the Show the Object library toolbar button (the black 3D cube) to display the UI components. Alternatively, simply select the View -> Utilities ->
Object Library menu option:

From the Object Library panel View -> Utilities -> Object Library, drag a Text Field object onto the View design area. Resize the object and position it so that it appears as follows:

Within the Attribute Inspector panel View -> Utilities -> Attribute Inspector, type the words Enter temperature into the Placeholder text field. This text will then appear in a light gray color in the text field as a visual cue to the user.
Now that we have created the text field for the user to enter the temperature into, the next step is to add a Button object that can be pressed to initiate the conversion. To achieve this drag and drop a Rounded Rect Button object from the Library to the View. Double click the button object so that it changes to text edit mode and type the word Convert onto the button. Finally, select the button and drag it beneath the text field until the blue dotted line appears indicating it is centered vertically in relation to the text field before releasing the mouse button.
The last user interface object we need to add is a label where the result of the conversion will be displayed. Add this by dragging a Label object from the Library window to the View and position it beneath the button. Stretch the width of the label so that it is approximately a third of the overall width of the view and reposition it using the blue guidelines to ensure it is centered in relation to the button.
Double click on the label to highlight the text and press the backspace key to clear the text (we will set the text from within a method of our View Controller class when the conversion calculation has been performed). Though the label is now no longer visible it is still present in the view. If you click where it is located it will be highlighted with the resize dots. At this point the user interface design phase of our project is complete and the view should appear as illustrated in the following figure. We now are ready to try out a test build and run.

Building and Running the Sample Application
Before we move on to writing the controller code for our application and then connecting it to the user interface we have designed we should first perform a test build and run of the application so far. Click on the Run button located in the toolbar to compile the application and run it in the simulator. If you are not happy with the way your interface looks feel free to reload it into Interface Builder and make improvements. Assuming the user interface appears to your satisfaction in the simulator we are ready to start writing some Objective-C code to add some logic to our controller. Exit from the simulator before proceeding to the next step by selecting the iOS Simulator -> Quit iOS Simulator menu option.
Adding Actions and Outlets
When the user enters a temperature value into the text field and touches the convert button we need to trigger an action that will perform a calculation to convert the temperature. The result of that calculation will then be presented to the user on the label object. The Action will be in the form of a method that we will declare and implement in our View Controller class. Access to the text field and label objects from the view controller method will be implemented through the use of Outlets.
The UIKit framework contains a class called UIViewController that provides the basic foundation for adding view controllers to an application. In order to create a functional application, however, we inevitably need to add functionality specific to our application to this generic view controller class. This is achieved by subclassing the UIViewController class and extending it with the additional functionality we need.
When we created our new project, Xcode anticipated our needs and automatically created a subclass of UIViewController and named it UnitConverterViewController (using as a prefix the name that we gave to our new project). In so doing, Xcode also created two source files; a header file named UnitConverterViewController.h and a source code file named UnitConverterViewController.m.
Selecting the UnitConverterViewController.h file in the Xcode project navigator panel will display the contents of the file in the editing pane:
As we can see from the above code, a new class called UnitConverterViewController has been created that is a subclass of the UIViewController class belonging to the UIKit framework.
The next step is to extend the subclass to include the two outlets and our action method. We will begin by adding outlets for our text field and label objects by declaring variables and using the IBOutlet keyword:
#import
@interface UnitConverterViewController : UIViewController {
UITextField *tempText;
UILabel *resultLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *resultLabel;
@property (nonatomic, retain) IBOutlet UITextField *tempText;
@end
Next we need to declare the action that will be called when the user touches the Convert button in our user interface. This is declared using the IBAction keyword:
#import
@interface UnitConverterViewController : UIViewController {
UITextField *tempText;
UILabel *resultLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *resultLabel;
@property (nonatomic, retain) IBOutlet UITextField *tempText;
- (IBAction)convertTemp:(id)sender;
@end
We have now declared that our View Controller class contains a method called convertTemp. Having made that declaration, we need to implement the method in the implementation source file. To do so, select the UnitConverterViewController.m file so that the contents appear in the editing pane:
#import "UnitConverterViewController.h"
@implementation UnitConverterViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)
nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
The first step is to instruct Objective-C to synthesize accessor methods for our tempText and resultLabel objects and then to implement the convertTemp method. The relevant section of the UnitConverterViewController.m file should now read as follows:
#import "UnitConverterViewController.h"
@implementation UnitConverterViewController
@synthesize resultLabel, tempText;
- (void) convertTemp: (id) sender {
double farenheit = [tempText.text doubleValue];
double celsius = (farenheit - 32) / 1.8;
NSString *resultString = [[NSString alloc]
initWithFormat: @"Celsius %f", celsius];
resultLabel.text = resultString;
[resultString release];
}
.
.
.
@end
Before we proceed it is probably a good idea to pause and explain what is happening in the above code. Those already familiar with Objective-C, however, may skip the next few paragraphs.
In this file we are implementing the convertTemp method that we declared in the .h file. This method takes as a single argument a reference to the sender. The sender is the object that triggered the call to the method (in this case our Button object). Whilst we won’t be using this object in the current example, this can be used to create a general purpose method in which the behavior of the method changes depending on how (i.e. via which object) it was called. We could, for example, create two buttons labeled Convert to Fahrenheit and Convert to Celsius respectively, each of which calls the same convertTemp method. The method would then access the sender object to identify which button triggered the event and perform the corresponding type of unit conversion.
Next, the code declares a variable of type double in order to handle the fact that the user may have entered a floating point value. We then use dot notation to access the text property (which holds the text displayed in the text field) of the UITextField object. This property is itself an object of type NSString. The NSString class has an instance method named doubleValue that converts the string value to a double. We therefore call this method on the text property and assign the result to our farenheit variable.
Having extracted the text entered by the user and converted it to a number we then perform the conversion to Celsius and store the result in another variable named celsius. Next, we create a new NSString object and initialize it with text that comprise the word Celsius and the result of our conversion. In doing so, we declare a pointer to this new object and call it resultText.
Finally, we use dot notation to assign the new string to the text property of our UILabel object so that it is displayed the user. The last step releases the memory that was allocated to the object referenced by resultText since it is no longer needed. Having created our action method we also need to modify the viewDidUnload and dealloc methods in this file to make sure we properly release the memory we allocated for our variables. Failure to do so will result in a memory leak in our application:
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.resultLabel = nil;
self.tempText = nil;
}
- (void)dealloc {
[resultLabel release];
[tempText release];
[super dealloc];
}
Before proceeding to the next section of this chapter, now is a good time to perform a build and run to make sure that no errors exist in the code. Click on the Run button in the toolbar and correct any syntax errors that are reported.
Connecting the Actions and Outlets to the User Interface
The final step in developing our application is to connect the actions and outlets we have declared in the view controller class to the actual objects in the user interface view. Fortunately, this can all be done visually from within the Interface Builder tool.
With this in mind, select the UnitViewController.xib file to load the user interface into Interface Builder. We will begin by connecting the IBOutlet instance variables we created in our view controller class to the label and text field objects respectively. Located in the narrow panel to the left of the graphical view of the user interface are three icons. Clicking on the small square with the black triangle at the bottom of this panel will expand the panel to provide more detail:

The top icon is the File’s Owner. This icon represents the file containing the class that invokes the user interface contained in the NIB file when the application runs. In this instance it is the UnitConverterViewController class, where we declared our actions and outlets.
To connect the resultLabel IBOutlet variable to the label object, hold down the Control key on the keyboard, click on the File’s Owner icon and drag the mouse to the location of the label object in the user interface design. A blue line will extend from the icon to the object as illustrated in the following figure:

Upon releasing the mouse button, Interface Builder will display a list of IBOutlet variables that match the type of the object selected:

Select resultLabel from the menu to complete the connection. Repeat these steps to connect the tempText outlet to the text field object. In order to view the connections you have created, display the Connections Inspector by selecting the far right hand toolbar option in the top section of the right hand panel or selecting View -> Utilities -> Connections Inspector. For example, the following figure shows the connection information for our label object:

The final step is to connect the button object to our convertTemp action method. Cocoa Touch objects typically have a wide range of events that can be triggered by the user. To obtain a full listing of the events available on a particular object, display the Connections Inspector View -> Utilities -> Connections Inspector and select the button object in the view window. Listed under Sent Events in the connections panel is a list of the events that can be triggered by the button object. In this instance, we are interested in the Touch Up Inside event. This event is triggered when a user touches the button and then releases their finger without first sliding it outside the boundaries of the button. When this action is performed we want our convertTemp method to be called. To make this connection, move the mouse pointer to the small circle next to the Touch Up Inside event in the connections panel, click the mouse button and drag to the File’s Owner icon as illustrated in the following figure:

Releasing the mouse button over the File’s Owner icon will display a menu with a list of methods available in the view controller class. In our case the only method is convertTemp so select that method to initiate the connection. The event listing in the Connections dialog will subsequently update to reflect the new connection.
Building and Running the Finished Application
From within the Xcode project window click on Run to compile the application and run it in the simulator. Once the application is running, click inside the text field and enter a Fahrenheit temperature. Next, click on the Convert button to display the equivalent temperature in Celsius. Assuming all went to plan your application should appear as outlined in the following figure (note that if the keyboard obscures the result label you will need to reload the user interface design into Interface Builder and move the label, button and text field objects so that they are all positioned in the top half of the view):
The purpose of the application we are going to create is to perform unit conversions from Fahrenheit to Centigrade. Obviously the first step is to create a new Xcode project to contain our application.
Start Xcode and on the Welcome screen select Create a new Xcode project. On the template screen choose the Application option located under iOS in the left hand panel and select View-based Application. Click Next, name the product UnitConverter, enter your company identifier and make sure that the Product menu is set to iPhone. On the final screen, choose a location in which to store the project files and click on Create to proceed to the main Xcode project window.
Creating the User Interface
Before we begin developing the logic for our interactive application we are going to start by designing the user interface. When we created the new project, Xcode generated an Interface Builder NIB file for us and named it UnitConverterViewController.xib. It is within this file that we will create our user interface, so select this file from the project navigator in the left hand panel to load it into Interface Builder. Once Interface Builder has loaded the file select the far right of the three View buttons in the Xcode toolbar to display the right hand panel. In the lower panel, select the Show the Object library toolbar button (the black 3D cube) to display the UI components. Alternatively, simply select the View -> Utilities ->
Object Library menu option:

From the Object Library panel View -> Utilities -> Object Library, drag a Text Field object onto the View design area. Resize the object and position it so that it appears as follows:

Within the Attribute Inspector panel View -> Utilities -> Attribute Inspector, type the words Enter temperature into the Placeholder text field. This text will then appear in a light gray color in the text field as a visual cue to the user.
Now that we have created the text field for the user to enter the temperature into, the next step is to add a Button object that can be pressed to initiate the conversion. To achieve this drag and drop a Rounded Rect Button object from the Library to the View. Double click the button object so that it changes to text edit mode and type the word Convert onto the button. Finally, select the button and drag it beneath the text field until the blue dotted line appears indicating it is centered vertically in relation to the text field before releasing the mouse button.
The last user interface object we need to add is a label where the result of the conversion will be displayed. Add this by dragging a Label object from the Library window to the View and position it beneath the button. Stretch the width of the label so that it is approximately a third of the overall width of the view and reposition it using the blue guidelines to ensure it is centered in relation to the button.
Double click on the label to highlight the text and press the backspace key to clear the text (we will set the text from within a method of our View Controller class when the conversion calculation has been performed). Though the label is now no longer visible it is still present in the view. If you click where it is located it will be highlighted with the resize dots. At this point the user interface design phase of our project is complete and the view should appear as illustrated in the following figure. We now are ready to try out a test build and run.

Building and Running the Sample Application
Before we move on to writing the controller code for our application and then connecting it to the user interface we have designed we should first perform a test build and run of the application so far. Click on the Run button located in the toolbar to compile the application and run it in the simulator. If you are not happy with the way your interface looks feel free to reload it into Interface Builder and make improvements. Assuming the user interface appears to your satisfaction in the simulator we are ready to start writing some Objective-C code to add some logic to our controller. Exit from the simulator before proceeding to the next step by selecting the iOS Simulator -> Quit iOS Simulator menu option.
Adding Actions and Outlets
When the user enters a temperature value into the text field and touches the convert button we need to trigger an action that will perform a calculation to convert the temperature. The result of that calculation will then be presented to the user on the label object. The Action will be in the form of a method that we will declare and implement in our View Controller class. Access to the text field and label objects from the view controller method will be implemented through the use of Outlets.
The UIKit framework contains a class called UIViewController that provides the basic foundation for adding view controllers to an application. In order to create a functional application, however, we inevitably need to add functionality specific to our application to this generic view controller class. This is achieved by subclassing the UIViewController class and extending it with the additional functionality we need.
When we created our new project, Xcode anticipated our needs and automatically created a subclass of UIViewController and named it UnitConverterViewController (using as a prefix the name that we gave to our new project). In so doing, Xcode also created two source files; a header file named UnitConverterViewController.h and a source code file named UnitConverterViewController.m.
Selecting the UnitConverterViewController.h file in the Xcode project navigator panel will display the contents of the file in the editing pane:
//
// UnitConverterViewController.h
// UnitConverter
//
// Created by Techotopia on 1/10/11.
// Copyright __MyCompanyName__ 2011. All rights reserved.
//
#import
@interface UnitConverterViewController : UIViewController {
}
@end
@interface UnitConverterViewController : UIViewController {
}
@end
As we can see from the above code, a new class called UnitConverterViewController has been created that is a subclass of the UIViewController class belonging to the UIKit framework.
The next step is to extend the subclass to include the two outlets and our action method. We will begin by adding outlets for our text field and label objects by declaring variables and using the IBOutlet keyword:
#import
@interface UnitConverterViewController : UIViewController {
UITextField *tempText;
UILabel *resultLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *resultLabel;
@property (nonatomic, retain) IBOutlet UITextField *tempText;
@end
Next we need to declare the action that will be called when the user touches the Convert button in our user interface. This is declared using the IBAction keyword:
#import
@interface UnitConverterViewController : UIViewController {
UITextField *tempText;
UILabel *resultLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *resultLabel;
@property (nonatomic, retain) IBOutlet UITextField *tempText;
- (IBAction)convertTemp:(id)sender;
@end
We have now declared that our View Controller class contains a method called convertTemp. Having made that declaration, we need to implement the method in the implementation source file. To do so, select the UnitConverterViewController.m file so that the contents appear in the editing pane:
#import "UnitConverterViewController.h"
@implementation UnitConverterViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)
nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
The first step is to instruct Objective-C to synthesize accessor methods for our tempText and resultLabel objects and then to implement the convertTemp method. The relevant section of the UnitConverterViewController.m file should now read as follows:
#import "UnitConverterViewController.h"
@implementation UnitConverterViewController
@synthesize resultLabel, tempText;
- (void) convertTemp: (id) sender {
double farenheit = [tempText.text doubleValue];
double celsius = (farenheit - 32) / 1.8;
NSString *resultString = [[NSString alloc]
initWithFormat: @"Celsius %f", celsius];
resultLabel.text = resultString;
[resultString release];
}
.
.
.
@end
Before we proceed it is probably a good idea to pause and explain what is happening in the above code. Those already familiar with Objective-C, however, may skip the next few paragraphs.
In this file we are implementing the convertTemp method that we declared in the .h file. This method takes as a single argument a reference to the sender. The sender is the object that triggered the call to the method (in this case our Button object). Whilst we won’t be using this object in the current example, this can be used to create a general purpose method in which the behavior of the method changes depending on how (i.e. via which object) it was called. We could, for example, create two buttons labeled Convert to Fahrenheit and Convert to Celsius respectively, each of which calls the same convertTemp method. The method would then access the sender object to identify which button triggered the event and perform the corresponding type of unit conversion.
Having extracted the text entered by the user and converted it to a number we then perform the conversion to Celsius and store the result in another variable named celsius. Next, we create a new NSString object and initialize it with text that comprise the word Celsius and the result of our conversion. In doing so, we declare a pointer to this new object and call it resultText.
Finally, we use dot notation to assign the new string to the text property of our UILabel object so that it is displayed the user. The last step releases the memory that was allocated to the object referenced by resultText since it is no longer needed. Having created our action method we also need to modify the viewDidUnload and dealloc methods in this file to make sure we properly release the memory we allocated for our variables. Failure to do so will result in a memory leak in our application:
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.resultLabel = nil;
self.tempText = nil;
}
- (void)dealloc {
[resultLabel release];
[tempText release];
[super dealloc];
}
Before proceeding to the next section of this chapter, now is a good time to perform a build and run to make sure that no errors exist in the code. Click on the Run button in the toolbar and correct any syntax errors that are reported.
Connecting the Actions and Outlets to the User Interface
The final step in developing our application is to connect the actions and outlets we have declared in the view controller class to the actual objects in the user interface view. Fortunately, this can all be done visually from within the Interface Builder tool.
With this in mind, select the UnitViewController.xib file to load the user interface into Interface Builder. We will begin by connecting the IBOutlet instance variables we created in our view controller class to the label and text field objects respectively. Located in the narrow panel to the left of the graphical view of the user interface are three icons. Clicking on the small square with the black triangle at the bottom of this panel will expand the panel to provide more detail:

To connect the resultLabel IBOutlet variable to the label object, hold down the Control key on the keyboard, click on the File’s Owner icon and drag the mouse to the location of the label object in the user interface design. A blue line will extend from the icon to the object as illustrated in the following figure:




From within the Xcode project window click on Run to compile the application and run it in the simulator. Once the application is running, click inside the text field and enter a Fahrenheit temperature. Next, click on the Convert button to display the equivalent temperature in Celsius. Assuming all went to plan your application should appear as outlined in the following figure (note that if the keyboard obscures the result label you will need to reload the user interface design into Interface Builder and move the label, button and text field objects so that they are all positioned in the top half of the view):

Unity Game Development
Unity 3 is a game development tool that has been designed to let you focus on creating amazing games. If you've tried Unity before, see whats new in 3.0. If this is your first time, take a look around or try Unity for yourself.
Free Full Version for OS X with Unity Pro, Android and iOS trials.
↓ Download Unity 3.3

System Requirements
System Requirements for Unity Authoring
- Windows: XP SP2 or later; Mac OS X: Intel CPU & "Leopard" 10.5 or later. Note that Unity was not tested on server versions of Windows and OS X.
- Graphics card with 64 MB of VRAM and pixel shaders or 4 texture units. Any card made in this millennium should work.
- Using Occlusion Culling requires GPU with Occlusion Query support (some Intel GPUs do not support that).
- The rest only depends on the complexity of your projects!.
- An Intel-based Mac
- Mac OS X "Snow Leopard" 10.6 or later
- The rest only depends on the complexity of your projects!
- In addition to the general system requirements for Unity Authoring
- Windows XP SP2 or later; Mac OS 10.5.8 or later
- Android SDK and Java Development Kit (JDK)
- Windows 2000 or later; Mac OS X 10.4 or later.
- Pretty much any 3D graphics card, depending on complexity.
- Online games run on all browsers, including IE, Firefox, Safari, and Chrome, among others.
- Android authored content requires devices equipped with:
- Android OS 2.0 or later
- Device powered by an ARMv7 (Cortex family) CPU
- GPU support for OpenGLES 2.0 is recommended
Unity WidgetsBuilding
Besides regular Mac apps, Unity can build MacOSX widgets, using the Unity web plugin.
The widgets are just a web player wrapped with the widget HTML. If you right/option-click on the .wdgt file and select Show Package, you'll see the generated Unity file and accompanying HTML, CSS and images. Any additional files loaded by the widget can be added in the widget. For example, this widget streams a movie, cat.ogv.You will probably want to customize the default Unity build by replacing the Icon.png file, which is the icon that displays in the Dashboard dock. Version information can be adjusted in the Info.plist file. You can customize the back panel by modifying the HTML and CSS files.
Publishing
Most widgets are submitted and listed on the Apple widget download page. Most widgets are free, though some are listed as shareware. If a widget is listed as a Staff Favorite or Featured Widget, it certainly ends up in the Top 50.
Widgets published include HyperBowl Classic, FuguBowl, FuguMaze, FuguTilt, FuguFlip, Fugutype...
Other Unity widgets include 3D Paradise Paintball, MacPinball, Banana Warehouse and Blingy.
References
See the Apple Dashboard developer article for an overview of widget and links to more articles.
WebKit Open Source Project
Here are some demo web applications that display various web technologies supported by WebKit.
Offline Calendar
Picking up where the sticky notes example leaves off, the Offline Calendar demo goes much more in depth into the power of the HTML 5 database API.
By storing the user's calendar events in a local databases and caching the application resources themselves using the HTML 5 application cache the calendar can be used with no network connection!
CSS Transitions and Transforms
This demo shows off how straight forward it is to add transforms and implicit animations to a web application by adding a small amount of CSS.
Check out our blog posts about CSS animations and CSS transforms for more details and examples.
Editing Toolbar
The editing toolbar shows off a rich HTML editing toolbar in WebKit. It uses JavaScript and CSS to fade in and out and to implement the buttons that apply text formatting and alignment. Click in the text area to see the toolbar appear.
Sticky Notes
Referenced about adding HTML 5 structured database storage, this is a simple example of how the database API works in the form of persistent yellow sticky notes.
Storing simple data, it is a great way for developers to introduce themselves to how the database API works.
Offline Calendar
Picking up where the sticky notes example leaves off, the Offline Calendar demo goes much more in depth into the power of the HTML 5 database API.
By storing the user's calendar events in a local databases and caching the application resources themselves using the HTML 5 application cache the calendar can be used with no network connection!
CSS Transitions and Transforms
This demo shows off how straight forward it is to add transforms and implicit animations to a web application by adding a small amount of CSS.
Check out our blog posts about CSS animations and CSS transforms for more details and examples.
Editing Toolbar
The editing toolbar shows off a rich HTML editing toolbar in WebKit. It uses JavaScript and CSS to fade in and out and to implement the buttons that apply text formatting and alignment. Click in the text area to see the toolbar appear.
Sticky Notes
Referenced about adding HTML 5 structured database storage, this is a simple example of how the database API works in the form of persistent yellow sticky notes.
Storing simple data, it is a great way for developers to introduce themselves to how the database API works.
Base SDK Missing

For the noobie iPhone App Developer, their reaction to the error message “Base SDK Mssing” on an xCode sample code project, is similar to how I once felt about the “Blue Screen of Death” on a PC.
I got that same feeling of frustration when I loaded down the PageControl sample code from Apple. I couldn’t test the sample code in xCode because the “Base SDK Missing” error message was on display. I was using xCode 3.
It wasn’t the first time I’d come across this error, however, previously I’d found a solution. I was desperately seeking a solution to paging horizontally and having PageControl.
I’ve solved my problems with the “Base SDK Missing” error message by trawling the internet and finding many generous people who share their knowledge. So this “post” is me giving back to the app development community a little of what I’ve learned.
Solving the “Base SDK Missing” Error
Sometimes you will try to open an old xCode project and you will find you can’t open it because the file gives you a “Base SDK Missing” message, as shown in the image below:

Base SDK Missing error message as seen on the xCode Dashboard
The first time I came across this problem I was working through John Ray’s Book “iPad Application Development in 24 hours”. The problem raised its ugly head again when I tried to open the PageControl sample code from Apple.
I came across the problem again when I found an article about sample code titled “How to Add A Slick iBooks Like Page Turning Effect Into Your Apps”, published by Johann “John” Dowa on his website ManiacDev. The article led me to a download for an xCode project called Leaves created by Tom Brow and an extension of the same project called “Leaves Two Pages” by Ole Begemann.
I couldn’t open the projects because they gave an error message i.e. Base SDK Missing. As mentioned, I’d had this message before but when I applied my solution, Solution 1, shock horror, it didn’t work. So I hunted around the internet for more solutions and found Solution 2. Both solutions are set out below:
Solution One for xCode 3
1) Select xCode File Name in the left side navigation bar and click on the blue Info button on the xCode Dashboard and a drop down menu will appear showing several tabs.

Screenshot showing selection of xCode File Name

xCode Dashboard Info Button

xCode Dashboard
2) Click on the Build Tab

Info Button Drop Down List showing Build Tab
3) Find “Base SDK” under Architecture section and select the appropriate version e.g. 4.2
4) Scroll down to Deployment Section and also set “OS Deployment Target” as 4.2
5) Close the xCode Project (do not close the xCode Program) then reopen the Project
This solution came partly from a member of the iPhone SDK Development Forum and a little tweaking by me.
If this did not fix the problem then follow the steps in solution two, as follows:
Sometimes, if the test file has been created in a very old xCode Program, you need to take more steps.
A solution for this problem was solved by a member of the “Leaves Developers” Google Group.
Solution Two
1) In xCode go to Targets and right click over the file name and select “Get Info”

Target Get Info Drop Down Menu
2) A drop down list will appear. Go to the Architecture section and click on the Base SDK Value field and select the correct iOS.

Target Architecture Drop Down Menu
3) Close the xCode Project (do not close the x Code program) and reopen the project. Hopefully you will then see that the Base SDK Missing message has disappeared and you are seeing “Simulator …

Simulator Button on the xCode Dashboard
Xcode Development

NSTableView class to create a single column table view
1. Create an Xcode project
- Step 01: Launch Xcode 3.0 and create a new project by clicking on File ⇒ New Project.
- Step 02: Select Application ⇒ Cocoa Application and click on the Next button.
- Step 03: Specify the Project Name and Project Directory as follows:
- Project Name: SingleColumnTableView
- Project Directory: ~/Documents/Project/XCode/Tutorial/SingleColumnTableView/
- Click on the Finish button.
2. Edit the NIB file
- Step 01: In the Groups & Files browser, expand the NIB Files folder and double click the MainMenu.nib file.
- a. Interface Builder NIB file browser
- b. Interface Builder Inspector
- c. Interface Builder Library
- d. Application Main Menu window
- e. Application Window
3. Create a controller class
- Step 01: Use Xcode to create the application controller class. In the Groups & Files browser, right click on the Classes folder ⇒ Add ⇒ New File.
- Step 02: Select Cocoa ⇒ Objective-C class and click on the Next button.
- Filename: ApplicationController.m
Double click on the ApplicationController.h file to view its interface specifications.
Double click on the ApplicationController.m file to view its implementation details.
- Step 03: Click on the Interface Builder icon to bring it to the foreground. Using the Interface Builder Library, select Objects & Controllers ⇒ Controllers ⇒ NSObject and drag it to the Interface Builder NIB file browser.
Using the Interface Builder Inspector, specify the following information:
- Class Identity ⇒ Class: ApplicationController
- Interface Builder Identify ⇒ Name: ApplicationController
You should now be able to see the reference to the ApplicationController class in the NIB file browser as shown below.
- Step 04: Specify an action that the application controller class can respond to.
Go to Class Actions, click on the button and specify an action called update:
- Step 05: Specify an outlet that will be used by the application controller class to communicate with the target table view object.
Leave the tableView type as id for the moment. The tableView type will be changed to NSTableView later on.
4. Create a table view and link it to the application controller class' outlet
- Step 01: Using the Interface Builder Library, click on the Objects tab and select the Views & Cells ⇒ Data Views folderr
- Step 02: Drag and drop an NSTableView object from the library to the application window. Resize the NSTableView object so that it is correctly positioned within the window. Leave a little space at the bottom of the window, so that we can later on, add a button to update the table view contents.
- Step 03: Since we're going to create a single column table view, we will need to delete the second table column using the Interface Builder NIB file browser.
Select the second Table Column and delete the object using the menu option Edit ⇒ Delete.
Your application window should now contain a single column table view.
- Step 04: Slowly click on the NSTableView object twice, to select the Table View object.
Ctrl+drag from the Table View object to the ApplicationController class to specify its dataSource and delegate outlets.
Right click on the Table View object to check the newly created associations for its dataSource and delegate outlets.
- Step 05: Select the ApplicationController class and ctrl+drag to the Table View object to its tableView outlet.
Using the Interface Builder, change the type for the tableView outlet to NSTableView.
5. Create a button and link it to the application controller class' update action
- Step 01: Using the Interface Builder Library, click on the Objects tab and select the Views & Cells ⇒ Buttons folder.
- Step 02: Drag and drop an NSButton from the library to the application window.
- Step 03: Select the Update button and ctrl+drag to the ApplicationController class in the Interface Builder NIB file browser.
6. Automatically generate source code and merge changes for the ApplicationController class
- Step 01: Select the ApplicationController in the Interface Builder NIB file browser and click on File ⇒ Write Class Files.
Click on Save.
Click on Merge. This will launch the FileMerge utility.
- Step 02: Merge changes to the ApplicationController.h file.
This will show the ApplicationController.h source code differences between the
- a. new source code that we just automatically generated using Interface Builder, on the left hand side
- b. previous source code that we had initially generated using Xcode, on the right hand side
- Difference #1: Select the first difference by pressing the ↓ down arrow key. We want to keep the changes on the right side so, press the → right arrow key. Alternatively, you can use the Actions drop down list to choose the difference to be selected for inclusion in the final merge.
- Difference#2: Select the difference on the left, since we don't want the extra line break.
- Difference#3: Select the difference on the left, since we want the IBOutlet NSTableView *tableView; entry to be included in the final merge.
- Difference#4: Select the difference on the left, since we want the - (IBAction)update:(id)sender; entry to be included in the final merge.
- Step 03: Merge changes to the ApplicationController.m file.
This will show the ApplicationController.m source code differences between the
- a. new source code that we just automatically generated using Interface Builder, on the left hand side
- b. previous source code that we had initially generated using Xcode, on the right hand side
- Difference #1: Select the difference on the right.
- Difference#2: Select the difference on the left, since we don't want the extra line break.
- Difference#3: Select the difference on the left, since we want the - (IBAction)update:(id)sender; entry to be included in the final merge.
Combine the files by selecting Merge ⇒ Combine Files.
Open the ApplicationController.h file to view the merged changes.
Open the ApplicationController.m file to view the merged changes.
7. Add a data source for the table view
- Step 01: Open the ApplicationController.h file and add a data source.
- // Data source
- @private NSMutableArray *aBuffer;
8. Implement NSTableView protocol methods for displaying table view contents
- Step 01: Implement the protocol method to retrieve the total number of rows in a table view.
- - (int)numberOfRowsInTableView:(NSTableView *)tableView{
- return ([aBuffer count]);
- }
- Step 02: Implement the protocol method to retrieve the object value for a table column.
- - (id)tableView:(NSTableView *)tableView
- objectValueForTableColumn:(NSTableColumn *)tableColumn
- row:(int)row{
- return [aBuffer objectAtIndex:row];
- }
9. Implement the Update button handler
- Step 01: Implement the ApplicationController update: method to print a log message to a console window and add a string object to the table view.
- - (IBAction)update:(id)sender {
- NSLog(@"The user has clicked the update button");
- [aBuffer addObject:@"HelloWorld"];
- [tableView reloadData];
- }
10. Implement the awakeFromNib and dealloc methods
- Step 01: In the awakeFromNib method, implement code to create and allocate memory for a new mutable array object.
- - (void)awakeFromNib{
- aBuffer = [NSMutableArray new];
- [tableView reloadData];
- }
- Step 02: In the dealloc method, implement code to release memory allocated to the mutable array object.
- - (void)dealloc{
- [aBuffer release];
- [super dealloc];
- }
11. Build and run the application
- Step 01: Display the Xcode console window by clicking on Run ⇒ Console.
- Step 02: In the Xcode project window, click on the Build and Go icon to build and launch the application.
- Step 03: Click on the Update button. This will create a row entry in the table view.
Document version: 1.0
Document date: 2008-03-08
Document reference: XCT_NSTVSC-1.0
Development tools: Xcode 3.0, Interface Builder 3.0.
Operating system: Mac OS X 10.5.2 (Leopard)
Handling button events
1. Create an Xcode project
- Step 01: Launch Xcode 3.0 by clicking on the Xcode application icon.
- Step 02: Click on File ⇒ New Project
- Step 03: Select Application ⇒ Cocoa Application and click on the Next button.
- Step 04: Specify the Project Name and Project Directory as follows:
Project Directory: ~/Documents/Project/XCode/Tutorial/HandlingButtonEvents/
Click on the Finish button.
This will bring up the Project window.
2. Edit the NIB file
- Step 01: In the Groups & Files browser, expand the NIB Files folder and double click the MainMenu.nib file
The Interface Builder (IB) application will display a set of windows for developing a Human Machine Interface (HMI):
- a. Interface Builder NIB file browser
- b. Interface Builder Inspector
d. Application Main Menu window
e. Application Window
3. Create a controller class
- Step 01: We will now use Xcode to create the application controller class. In the Groups & Files browser, right click on the Classes folder ⇒ Add ⇒ New File.
- Step 02: Select Cocoa ⇒ Objective-C class and click on the Next button.
Filename: ApplicationController.m
You should now be able to see the files for the ApplicationController class will be automatically added to the Xcode project.
Double click on the ApplicationController.h file to view its interface specifications.
Double click on the ApplicationController.m file to view its implementation details.
- Step 03: Click on the Interface Builder icon to bring it to the foreground. Using the Interface Builder Library, select Objects & Controllers ⇒ Controllers ⇒ NSObject and drag it to the Interface Builder NIB file browser.
Class Identity ⇒ Class: ApplicationController
Interface Builder Identify ⇒ Name: ApplicationController
Because Interface Builder is automatically synchronized with Xcode, you can see the ApplicationController class that was previously created in Xcode, in the drop-down list box for the class identify.
You should now be able to see the reference to the ApplicationController class in the NIB file browser as shown below.
- Step 04: Specify an action that the application controller class can respond to.
Using Interface Builder, click on File ⇒ Write Class Files to to update the source files for the application controller class.
Click on the Save button.
Click on the Replace button to overwrite the existing application controller class files.
Double click on the ApplicationController.h file from the Xcode project browser window.
Observe the newly added action method entry in the interface file
- - (IBAction)update:(id)sender;
Observe the newly added action method implementation entry in the implementation file
- - (IBAction)update:(id)sender {
- }
- Step 05: Implement the update action method for the application controller class.
- - (IBAction)update:(id)sender {
- NSLog(@"The user has clicked the update button");
- }
4. Create a button and link it to the application controller class' update action
- Step 01: Using the Interface Builder Library, click on the Objects tab and select the Views & Cells folder.
- Step 02: Drag and drop an NSButton from the library to the application window.
- Step 03: Select the Update button and ctrl+drag to the ApplicationController class in the Interface Builder NIB file browser.
Select the Update button and view the button connections using the Interface Builder Inspector.
Select the ApplicationController class from the Interface Builder NIB file browser and view the application controller class connections.
5. Build and run the application
- Step 01: Display the Xcode console window by clicking on Run ⇒ Console
- Step 02: In the Xcode project window, click on the Build and Go icon to build and launch the application.
- Step 03: Click on the Update button.
Dashboard Widget Tutorial
This tutorial walks you through using Dashcode to create a Dashboard widget. As you follow the steps, you learn how to choose a widget template, customize your widget’s appearance and code, and share your widget with others. Completing this tutorial is a quick and easy way to get started building Dashboard widgets in Dashcode.
This document includes two additional tutorials, “Mobile Safari Web Application Tutorial” and “Dual-Product Web Application Tutorial,” which follow this one. The remainder of the document delves more deeply into the Dashcode development environment, describing how it supports both widget and web application development. If you don’t want to learn how to create a web application, you can continue learning more about Dashcode by reading “Starting a Project.”
Before You Begin !
In this tutorial, you build a Dashboard widget that counts down to your birthday, similar to the widget shown in Figure 1-1.
Figure 1-1 The Birthday widget

Before continuing, make sure that you have Dashcode installed on your Mac (the location is /Developer/Applications/). If you don’t have Dashcode installed, read “Getting and Running Dashcode” to learn how to get and install Dashcode.
Choose a Template
To start, double-click the Dashcode icon to open it. A new project window opens and displays a dialog in which you first select the type of project you’re interested in—in this case, Dashboard—and then, the kind of widget you want to create from an assortment of templates. Templates are handy starting points for creating common types of widgets. Select a template’s icon to show a short description of what that template does.
To make the Birthday widget, this tutorial uses the Countdown template. Select its icon and click Choose. A project window opens with a new widget based on the Countdown template, as shown in Figure 1-2.
Figure 1-2 A project window showing a new Dashboard widget
Along the left side of the project window is the navigator, which you use to switch between the various tools available when you’re designing a widget. The main portion of the window is the canvas, which you use to design your widget’s interface.
At the bottom of the navigator in Figure 1-2 you can see the Workflow Steps list, which guides you through the widget development process. Each step is a milestone in creating a widget, telling you what to do and where to do it. When you complete a step, mark it as done and move on to the next step.
Note: If you don’t want to see the Workflow Steps list, you can hide it by choosing View > Steps or by clicking the button that looks like a checkbox at the bottom edge of the project window (this button is highlighted in Figure 1-2).
Alternatively, you can view a list of the widget’s files in place of the Workflow Steps list. If you want to see the Files list, choose View > Files or click the list button in the bottom edge of the project window (it’s the button that looks like a bulleted list).
Set the Target Date
The Countdown template gives you a Dashboard widget with all the elements and code needed to count down to an event. All you need to do is tell the widget the target date. To set the target date, select Widget Attributes in the navigator. The canvas is replaced by the widget attributes pane, in which you specify important values that your widget needs.
In the Properties section of the widget attributes pane, choose Date and Time in the Target Kind pop-up menu and enter the date of your next birthday, as shown in Figure 1-3.
Figure 1-3 The Countdown template’s properties

Test the Countdown
Your new Dashboard widget is already fully functional. To prove this, choose Debug > Run to run the widget. Dashcode can run a widget without opening it in Dashboard, making it a handy place to test your widget and fix any problems you encounter. After the widget loads, it starts counting down towards your next birthday.
When you’re satisfied that your widget is working as you expect, choose Debug > Stop to stop it.
Now is a good time to save your widget project. Choose File > Save to save the project. Give your project a name and select a location to save it in. Your widget is saved in a widget project that encapsulates the widget and information Dashcode needs to create the widget for you.
Customize the Widget’s Appearance
Although you now have a fully functioning Dashboard widget that’s ready to share, you might want to personalize it to make it unique. Dashcode’s design tools make it easy to customize your widget’s interface. Select the widget item in the navigator (it should display the name you gave it when you saved the project). The widget attributes pane is replaced with the canvas.
First, change your widget’s body color. Select the widget body (also called the front image or frontImg) on the canvas and then choose Window > Show Inspector. The inspector window allows you to modify a selected element’s properties, such as its appearance and behavior. Click the Fill & Stroke button at the top of the inspector window (it’s the second from the left). If it’s not already selected, click the Style tab to reveal fill, stroke, corner roundness, and opacity values. Click the color well and choose a new color in the Colors window that appears. Try different fill styles until you find a combination that you like. If you want to try changing other effects, such as the glass appearance, click the Effects tab to reveal these values, as shown in Figure 1-4.
Figure 1-4 Tweaking the front image using the Fill & Stroke inspector

When you’re finished customizing your widget’s body, add a photo of yourself from iPhoto to the widget. Your iPhoto library is available from the Library window. To show your iPhoto library, choose Window > Show Library; then click the Photos button. Find a photo and drag it to your widget on the canvas. Resize it by dragging any of the resize handles on the photo.
Finally, change the Event Label text to something like “...days until my birthday.“ You can do this by selecting the Event Label text, clicking the Attributes button in the inspector window (it’s the leftmost button), and entering the text in the Value field, or by double-clicking the text in the widget body itself and entering the new text.
Add Functionality Using Parts
Now that you have a personalized Dashboard widget that counts down to your birthday, add a button that, when clicked, shows the Apple Store (so your friends and family can buy you a birthday present!). To add a button to your widget, use a button part. Parts are controls and views used on a widget’s interface.
To find a button part, choose Window > Show Library and click Parts. You can use the search field at the bottom of the window to help you find a particular part or type of part. From the list of parts, drag the Lozenge Button part from the Library window to your widget’s body. Double-click the button to select its label text, enter the text “Buy me a gift” and press Return. You'll probably need to resize the button to fit the new label.
Write Code to Show the Apple Store
To make the button take the user to the Apple Store when it’s clicked, you need to add a behavior to the button. In the inspector window, click the Behaviors button (it’s the rightmost button). This shows the Behaviors pane, in which you assign handler functions to events on an object. Select the button on the canvas and double-click in the Handlers column next to the onclick event name. Enter the name of a new function, such as showAppleStore, and press Return. Click the arrow next to the function name you entered to reveal the source code editor below the canvas. Here you write code to add functionality to your widget. Clicking the arrow reveals the showAppleStore function Dashcode inserted in your widget’s code. Between the braces ({ .. }) enter the following line of code:
widget.openURL("http://store.apple.com/");
The code in the source code editor should look like that in Figure 1-5.
Figure 1-5 A function in the source code editor

Test your widget again by choosing Debug > Run. Click the button you added and make sure a new Safari window opens with the Apple Store website displayed. Be sure you save your project often to preserve the changes you make.
Deploy Your Widget
Congratulations! You’ve created your first complete Dashboard widget using Dashcode.
To open your widget in Dashboard, choose File > Deploy Widget. Click Install in the dialog that appears to view your widget in Dashboard.
To share your widget with the world, select Run & Share in the navigator. The pane that appears displays the widget project name you chose in “Test the Countdown,” but you can replace this with a different name if you want. You can also set the minimum version of Mac OS X your widget should run in. Click Save to Disk to save your widget. You can now email it to friends or post it on your webpage. You can use the File > Compress command in the Finder to archive it.
This document includes two additional tutorials, “Mobile Safari Web Application Tutorial” and “Dual-Product Web Application Tutorial,” which follow this one. The remainder of the document delves more deeply into the Dashcode development environment, describing how it supports both widget and web application development. If you don’t want to learn how to create a web application, you can continue learning more about Dashcode by reading “Starting a Project.”
Before You Begin !
In this tutorial, you build a Dashboard widget that counts down to your birthday, similar to the widget shown in Figure 1-1.
Figure 1-1 The Birthday widget

Before continuing, make sure that you have Dashcode installed on your Mac (the location is /Developer/Applications/). If you don’t have Dashcode installed, read “Getting and Running Dashcode” to learn how to get and install Dashcode.
Choose a Template
To start, double-click the Dashcode icon to open it. A new project window opens and displays a dialog in which you first select the type of project you’re interested in—in this case, Dashboard—and then, the kind of widget you want to create from an assortment of templates. Templates are handy starting points for creating common types of widgets. Select a template’s icon to show a short description of what that template does.
To make the Birthday widget, this tutorial uses the Countdown template. Select its icon and click Choose. A project window opens with a new widget based on the Countdown template, as shown in Figure 1-2.
Figure 1-2 A project window showing a new Dashboard widget
Along the left side of the project window is the navigator, which you use to switch between the various tools available when you’re designing a widget. The main portion of the window is the canvas, which you use to design your widget’s interface.
At the bottom of the navigator in Figure 1-2 you can see the Workflow Steps list, which guides you through the widget development process. Each step is a milestone in creating a widget, telling you what to do and where to do it. When you complete a step, mark it as done and move on to the next step.
Note: If you don’t want to see the Workflow Steps list, you can hide it by choosing View > Steps or by clicking the button that looks like a checkbox at the bottom edge of the project window (this button is highlighted in Figure 1-2).
Alternatively, you can view a list of the widget’s files in place of the Workflow Steps list. If you want to see the Files list, choose View > Files or click the list button in the bottom edge of the project window (it’s the button that looks like a bulleted list).
Set the Target Date
The Countdown template gives you a Dashboard widget with all the elements and code needed to count down to an event. All you need to do is tell the widget the target date. To set the target date, select Widget Attributes in the navigator. The canvas is replaced by the widget attributes pane, in which you specify important values that your widget needs.
In the Properties section of the widget attributes pane, choose Date and Time in the Target Kind pop-up menu and enter the date of your next birthday, as shown in Figure 1-3.
Figure 1-3 The Countdown template’s properties

Test the Countdown
Your new Dashboard widget is already fully functional. To prove this, choose Debug > Run to run the widget. Dashcode can run a widget without opening it in Dashboard, making it a handy place to test your widget and fix any problems you encounter. After the widget loads, it starts counting down towards your next birthday.
When you’re satisfied that your widget is working as you expect, choose Debug > Stop to stop it.
Now is a good time to save your widget project. Choose File > Save to save the project. Give your project a name and select a location to save it in. Your widget is saved in a widget project that encapsulates the widget and information Dashcode needs to create the widget for you.
Customize the Widget’s Appearance
Although you now have a fully functioning Dashboard widget that’s ready to share, you might want to personalize it to make it unique. Dashcode’s design tools make it easy to customize your widget’s interface. Select the widget item in the navigator (it should display the name you gave it when you saved the project). The widget attributes pane is replaced with the canvas.
First, change your widget’s body color. Select the widget body (also called the front image or frontImg) on the canvas and then choose Window > Show Inspector. The inspector window allows you to modify a selected element’s properties, such as its appearance and behavior. Click the Fill & Stroke button at the top of the inspector window (it’s the second from the left). If it’s not already selected, click the Style tab to reveal fill, stroke, corner roundness, and opacity values. Click the color well and choose a new color in the Colors window that appears. Try different fill styles until you find a combination that you like. If you want to try changing other effects, such as the glass appearance, click the Effects tab to reveal these values, as shown in Figure 1-4.
Figure 1-4 Tweaking the front image using the Fill & Stroke inspector

When you’re finished customizing your widget’s body, add a photo of yourself from iPhoto to the widget. Your iPhoto library is available from the Library window. To show your iPhoto library, choose Window > Show Library; then click the Photos button. Find a photo and drag it to your widget on the canvas. Resize it by dragging any of the resize handles on the photo.
Finally, change the Event Label text to something like “...days until my birthday.“ You can do this by selecting the Event Label text, clicking the Attributes button in the inspector window (it’s the leftmost button), and entering the text in the Value field, or by double-clicking the text in the widget body itself and entering the new text.
Add Functionality Using Parts
Now that you have a personalized Dashboard widget that counts down to your birthday, add a button that, when clicked, shows the Apple Store (so your friends and family can buy you a birthday present!). To add a button to your widget, use a button part. Parts are controls and views used on a widget’s interface.
To find a button part, choose Window > Show Library and click Parts. You can use the search field at the bottom of the window to help you find a particular part or type of part. From the list of parts, drag the Lozenge Button part from the Library window to your widget’s body. Double-click the button to select its label text, enter the text “Buy me a gift” and press Return. You'll probably need to resize the button to fit the new label.
Write Code to Show the Apple Store
To make the button take the user to the Apple Store when it’s clicked, you need to add a behavior to the button. In the inspector window, click the Behaviors button (it’s the rightmost button). This shows the Behaviors pane, in which you assign handler functions to events on an object. Select the button on the canvas and double-click in the Handlers column next to the onclick event name. Enter the name of a new function, such as showAppleStore, and press Return. Click the arrow next to the function name you entered to reveal the source code editor below the canvas. Here you write code to add functionality to your widget. Clicking the arrow reveals the showAppleStore function Dashcode inserted in your widget’s code. Between the braces ({ .. }) enter the following line of code:
widget.openURL("http://store.apple.com/");
The code in the source code editor should look like that in Figure 1-5.
Figure 1-5 A function in the source code editor

Test your widget again by choosing Debug > Run. Click the button you added and make sure a new Safari window opens with the Apple Store website displayed. Be sure you save your project often to preserve the changes you make.
Deploy Your Widget
Congratulations! You’ve created your first complete Dashboard widget using Dashcode.
To open your widget in Dashboard, choose File > Deploy Widget. Click Install in the dialog that appears to view your widget in Dashboard.
To share your widget with the world, select Run & Share in the navigator. The pane that appears displays the widget project name you chose in “Test the Countdown,” but you can replace this with a different name if you want. You can also set the minimum version of Mac OS X your widget should run in. Click Save to Disk to save your widget. You can now email it to friends or post it on your webpage. You can use the File > Compress command in the Finder to archive it.




Safari
10.7
10.8