Developing First IPhone Application

In this tutorial you will get a brief introduction on how to get started with your first iPhone application. To begin you will need the latest version of the iPhone SDK. With the SDK you get some tools like Xcode, Interface Builder, iPhone simulator etc.

Purpose of the “Hello Friend” app Using the app a user will be able to enter his/her full name and click a button to see a message appear. The message will say “Hello Friend, my name is ……!” This app will not only introduce you to some of its tools but will also show you how to use controls, respond to events and create new views.

Creating a new project Launch Xcode and click on File -> New Project -> Select Application (under iPhone OS) -> select Window-> Based Application project template and click on choose. In the next screen you will be asked to save your project and give it a name. Xcode creates some files for us based on the name of the project, so you need to be careful with the name you provide. Here the name given to the project is “HelloFriend”. All the class files are stored under the “Classes” folder, some special files are listed under “Other Sources”, all the view files and resources show up under “Resources”, and any library or frameworks we add to our project are listed under the “Frameworks” folder. It is important that we save all the images, files, databases, and views in the “Resources” folder because all the iPhone apps run in its own sand box; which means it can only access files placed under the resources folder.

Interface Builder Using Interface Builder we can design our application by adding controls or creating additional views. The files that the Interface Builder creates get saved with a .xib extension and are called nib files. Every project gets one nib file which is called “MainWindow.xib” which can be found under “Resources”. An iPhone application has only one window (MainWindow.xib) unlike a desktop application which is created with multiple windows; however, we can create multiple views which are added to the window. Double click on “MainWindow.xib” to launch the Interface Builder. Every nib file has at least two files; File’s Owner and First Responder which cannot be deleted. Every other objects apart from the first two, represents an instance of an object which gets created when the nib file loads. File’s Owner simply shows that it owns the object in the nib file. First Responder tells us which object are we currently interacting with; like the textbox, buttons. The third object which is special to the MainWindow.xib file is called “Hello Friend App Delegate” and this file represents “HelloFriendAppDelegate” class. Last but not the least the view represents the object which we design in our apps.

Creating a new view If we had created this project using “View-Based Application” project template then there would have been no need of creating another view from scratch, but where is the fun in that. In Interface Builder create a new view by clicking File -> New -> Select Cocoa Touch -> View and click on choose. Let’s save the view in the project folder by naming it “HelloFriend” and once we are done with that IB (Interface Builder) will prompt us to add the view to the current project; click on “Add” and it will show up in Xcode. In Xcode move your view to the Resources folder.

Creating a view controller We have a view; now let’s create a view controller to manage the view. In Xcode create a new view controller by selecting classes and clicking File -> New File -> Select Cocoa Touch Classes under iPhone OS -> select UIViewController -> click on choose and name your file “HelloFriendController” without changing the extension. The newly created class inherits from UIViewController which knows how to interact with a view. Now that we have our view and the controller class, there must be some way to connect these two files and we can do it by setting the class property of the File’s Owner. Double click “HelloFriend.xib” file in Xcode to launch Interface Builder and select File’s Owner->select Tools->Identity Inspector and under “Class Identity” category, change the class to “HelloFriendController”. Once we are done with this, we need a way to control the view in the nib file from code and this could be done by connecting the view instance variable to the view object in the nib. The connection is made using “outlets”. Select Tools -> Connections Inspector create a connection from the view variable to the view in the nib file. Move your mouse over the empty circle to see it change to a plus symbol indicating that a connection can be created. Click on circle and drag your mouse to the view in the nib file and release. As you do this you will see a blue line being created from the circle to the mouse.

Adding controls to the view We require two text boxes, one label, and a button (Round Rect Button). From the library drag and drop the controls to the view and align it. After you have added the controls let’s change some of its properties, starting with the text boxes. Select the first text box and open Attributes Inspector by selecting Tools -> Attributes Inspector. Under Placeholder enter “First name”, under “Text Input Traits” change Capitalize property to “Words” and change the Return key property to “Done”. Apply the same settings for the other text box but change the Placeholder to say “Last name”. Select the label and delete its text property, since we do not want the label to say anything until the button is clicked. Double-click the button to edit the title of the button and type in “Click Me”. Save and quit Interface Builder as we have successfully designed our view.

Connecting instance variables to the objects in the view We still need some way to interact with the controls on the view, in code and this is where outlets will help us out. IBOutlet is a special keyword if used with an instance variable, will make the variable appear in Interface Builder. Since IBOutlet makes the variable appear in Interface Builder, using IBAction as a return type for a method will have the opposite effect. Using IBAction we can handle an event triggered by any control placed on the view. Let’s see how this works; open HelloFriendController.h file in Xcode and type  the following code

@interface HelloFriendController: UIViewController {
IBOutlet UITextField *txtFirstName;
IBOutlet UITextField *txtLastName;
IBOutlet UILabel *lblMessage;
- (IBAction) btnClickMe_Clicked:(id)sender;
- (void)dealloc {
[txtFirstName release];
[txtLastName release];
[lblMessage release];
[super dealloc];

All the variables above are marked with IBOutlet and Interface Builder will make these available to itself, so proper connections can be made. We also have a method whose return type is IBAction (void); Interface Builder will also make this method available to itself so we can choose which event will call this method. The method also takes a parameter called “sender” which is the object which triggered the event. The variables are released in the dealloc method as shown above. Let’s connect these instance variables to the controls on the view (HelloFriend) as described earlier. Open Interface Builder by double-clicking HelloFriend.xib file and select File’s Owner, open Connections Inspector to see all the variables present under Outlets and to create connections. Let’s hook up the button click event to the “btnClickMe_Clicked” method. Select the button and under the Events list it seems that we do not have a button click event; however, we do have a “Touch up Inside” event which is raised when the button is touched and released symbolizing a click. With the button selected click the circle next to “Touch Up Inside” and drag your mouse over to File’s Owner and release to have the method name show; simply click on the method name to create a connection.

Handling events Let’s write some code in btnClickMe_Clicked event to read the first and last name and display a message in the label. This is how the code looks like

- (IBAction) btnClickMe_Clicked:(id)sender {
NSString *FirstName = txtFirstName.text;
NSString *LastName = txtLastName.text;
NSString *Message = nil;
if([FirstName length] == 0 && [LastName length] == 0)
Message = [[NSString alloc] initWithFormat:@"Hello Friend!!!"];
else if ([FirstName length] > 0 && [LastName length] ==0)
Message = [[NSString alloc] initWithFormat:@"Hello Friend, my name is %@!", FirstName];
else if ([FirstName length] == 0 && [LastName length] == 0)
Message = [[NSString alloc] initWithFormat:@"Hello Friend, my name is %@!", LastName];
Message = [[NSString alloc] initWithFormat:@"Hello Friend, my name is %@ %@!", FirstName, LastName];
lblMessage.text = Message;
//Release the object
[Message release];

The method does few simple things; it finds out the first and last names and figures out what message to display in the label. We also create a temporary variable called “Message” to hold the message which will be displayed in the label. The variable is allocated and initialized by alloc and initWithFormat messages respectively. The variable is released in the end because when working with the iPhone we are responsible of cleaning up the memory. The easiest way to remember when to release objects is; if you create it then you own the object and hence you are responsible of releasing it. If you click on Build and Go, the view will not be visible because we have not yet added it to the window. Let’s see how we can do that.

Adding view to the window Now we cannot drag the view and add it to the window, so we need another way to add the view as a sub view to the window. We already know that “HelloFriendController” is the view controller of the view “HelloFriend” and “HelloFriendAppDelegate” is the application delegate where the window is made visible in applicationDidFinishLaunching method. It is in that method we will add the view as a sub view to the window. Before we do that, the application delegate (HelloFriendAppDelegate) needs to know about our view controller. Add the following lines to HelloFriendAppDelegate.h file to change the file like this

@class HelloFriendController;
@interface HelloFriendAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
HelloFriendController *hvController;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) HelloFriendController *hvController;

From the above code we first add a forward class declaration of “HelloFriendController” because we do not want any circular dependency when we import the header file of “HelloFriendController” in HelloFriendAppDelegate.m. A variable and a property of type HelloFriendController is also declared. The property as you can see is declared with a couple of attributes called “retain” and “nonatomic”. The retain attribute will increase the reference count of the instance variable by one and nonatomic is used because our program is not multi-threaded. A lot of first time users miss to synthesize the property we declared, so let’s do that now at the top of the HelloFriendAppDelegate.m file and the code looks like this

@implementation HelloFriendAppDelegate
@synthesize window, hvController;

The view is added as a sub view to the window in applicationDidFinishLaunching method and this is how the code looks like

- (void)applicationDidFinishLaunching:(UIApplication *)application {
HelloFriendController *hvc = [[HelloFriendController alloc]
initWithNibName:@"HelloFriend" bundle:[NSBundle mainBundle]];
self.hvController = hvc;
[hvc release];
[window addSubview:[self.hvController view]];
// Override point for customization after application launch
[window makeKeyAndVisible];

The second line shows that we imported the header file of “HelloFriendController” and we also synthesized the property hvController. In the “earlier” days in order to create a property we had to create getter and setter methods which would be something like getHVController and setHVController. The synthesize keyword automatically generates these methods for us. In applicationDidFinishLaunching method we allocate and initialize a temporary variable, assign it to our property, release it, and the view associated with the view controller is added as a sub view to the window. The key thing to remember here is that the view message is passed to the “hvController” which returns the view and is added as sub view to the window. A valid view is returned because we created a connection from the view instance variable to the view in the nib file. The property is finally released in the dealloc method as shown below

- (void)dealloc {
[hvController release];
[window release];
[super dealloc];

We have always allocated and initialized variables in one single line as seen below, this is usually the accepted way but the same code can be written in a different way as seen below:

HelloFriendController *hvc = [HelloFriendController alloc];
hvc = [hvc initWithNibName:@"HelloFriend" bundle:[NSBundle mainBundle]];
Build and go to test your application.

Hiding the keyboard Wait a minute; clicking the “Done” button doesn’t do anything. Ideally we would like to hide the keyboard when the “Done” button is clicked no matter which text box we are currently editing. To hide the keyboard we need to do two things; set the delegate of the keyboard to File’s Owner and implement a method called textFieldShouldReturn in HelloFriendController.m file. To set the delegate, open Interface Builder by double clicking HelloFriend.xib, select the first text box and click on Tools -> Connections Inspector. Click and drag your mouse by selecting the empty circle next to delegate under “Outlets” and release your mouse over to File’s Owner. Assign the delegate for the next text box in the same manner. The method textFieldShouldReturn gets called when the “Done” button is clicked and this is how the code looks like

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;

The method gets a parameter called sender, which is the object that triggered the event. We will use the same object to which we send the resignResponder message, which will hide the keyboard on the textbox. The boolean “Yes” is returned to tell the sender that the first responder is resigned.

Conclusion We hope that you had fun with this tutorial and feel a little confident in writing your next great iPhone app. Please leave your comments and share your thought with us. Happy Programming!

PS: We have re-written this tutorial hoping that it would be easier to follow. If you have any questions please do not hesitate to send your revert here and we will be happy to help you out.