In this tutorial you will learn to
- Create a new project
- Create a view
- Create a view controller
- To add a view to the window.
- Event handling.
- Connect the controls on the view to the view controller objects.
Lets get started by opening Xcode, you can close the welcome screen that you see. Create a new project by clicking on File-> New Project and selecting Window-Based Application from iPhone OS. Name your project "HelloUniverse" and save it. The window that you see in front of you is the Xcode IDE. Note: If you have named your project something else, then the name of your files will be different then the ones I speak of here.
Some of the files required to run the application is already created for you. One of the important file is called main.m and it has one method called main which takes two arguments and returns an integer. Almost any iPhone application you create, the main method will look similar to this one. The other important detail of the project is the application delegate, in our project it is called HelloUniverseAppDelegate, where the class is declared in the header file (denoted by a .h extension) and the class is implemented in the implementation file (denoted by a .m extension). You have just created your first iPhone application, click on Build and Go to find out for yourself.
What you are seeing is the application running in the iPhone simulator. This does not do anything useful, except display a white screen. Lets add some functionality to it.
Writing applications for iPhone is a completely new experience on a different device. There are few things you need to remember, when creating applications for the iPhone.
To create a new view, we have to create a nib file. nib file is your user interface that you design using the Interface Builder. Interface Builder comes with the SDK. As the name suggest Interface Builder is visual tool which you will use to create your window, views and establish relationship between the views and other objects in the application. A nib file has a .xib extension. One file is already created for us which is the main window. The same window which we saw in the iPhone simulator.
Double click the MainWindow.xib file to launch the Interface Builder.
MainWindow.xib has four objects
1. File's Owner - This is the instance of the UIApplication.
2. First Responder - This is used to handle multi-touch events. More about this in the future tutorials.
3. Hello Universe App Delegate - Responsible for displaying the window and setting up the initial view. It is also responsible to restore the application to its previous state, handle memory warnings, responding to changes in the orientation of the device. It is set to an instance of the HelloUniverseAppDelegate class. You can find this out by selecting the delegate and click on Tools -> Identity Inspector. As shown in the image below.
4. Window - This is the window which we see when the application loads.
To create a new view using Interface Builder, click on File -> New and Select "View". You will see a new view created. First, we need to save this view and add it to our Xcode project. To do this, select the view and click on File -> Save, select the location to save the view (in your project folder) , name your view "HelloView" and click on save. As soon as you save the file, you will be prompted to add the view in your Xcode project, select the project and click on add.
Go to Xcode and drag your view under resources. This is where your nib files should be placed.
Now we have created our view. Let us add some controls to the view. You can do this by double clicking the view and adding objects to it from the library. If you do not see the library, you can open it by clicking Tools -> Library.
Let us add two text boxes, a label and a button.
Your view should look something like this

What you are seeing is the application running in the iPhone simulator. This does not do anything useful, except display a white screen. Lets add some functionality to it.
Writing applications for iPhone is a completely new experience on a different device. There are few things you need to remember, when creating applications for the iPhone.
- An iPhone application can only have one window. We will create views which can then be added to the window.
- iPhone OS does not support memory management using the garbage collection feature that is in Mac OS Xv10.5 or later.
To create a new view, we have to create a nib file. nib file is your user interface that you design using the Interface Builder. Interface Builder comes with the SDK. As the name suggest Interface Builder is visual tool which you will use to create your window, views and establish relationship between the views and other objects in the application. A nib file has a .xib extension. One file is already created for us which is the main window. The same window which we saw in the iPhone simulator.
Double click the MainWindow.xib file to launch the Interface Builder.
MainWindow.xib has four objects
1. File's Owner - This is the instance of the UIApplication.
2. First Responder - This is used to handle multi-touch events. More about this in the future tutorials.
3. Hello Universe App Delegate - Responsible for displaying the window and setting up the initial view. It is also responsible to restore the application to its previous state, handle memory warnings, responding to changes in the orientation of the device. It is set to an instance of the HelloUniverseAppDelegate class. You can find this out by selecting the delegate and click on Tools -> Identity Inspector. As shown in the image below.
4. Window - This is the window which we see when the application loads.
To create a new view using Interface Builder, click on File -> New and Select "View". You will see a new view created. First, we need to save this view and add it to our Xcode project. To do this, select the view and click on File -> Save, select the location to save the view (in your project folder) , name your view "HelloView" and click on save. As soon as you save the file, you will be prompted to add the view in your Xcode project, select the project and click on add.
Go to Xcode and drag your view under resources. This is where your nib files should be placed.
Now we have created our view. Let us add some controls to the view. You can do this by double clicking the view and adding objects to it from the library. If you do not see the library, you can open it by clicking Tools -> Library.
Let us add two text boxes, a label and a button.
Your view should look something like this

Let us set some properties of our controls. Select the first text field and select the Attributes Inspector (Tools -> Attributes Inspector). Enter "First Name" for Placeholder, Under Text Input Traits select Words for capitalize, Name Type Phone Pad for Type and Done for return key. Also select "Clear Context before Drawing" under view. This will clear the text before rewriting. Apply the same settings for the second text field as well but enter "Last Name" for placeholder.
Double click the button and enter "Click ME!!!". This can also be done by selecting the button and changing the Title property in the Attributes Inspector. Select the label and make sure that "Clear Context before Drawing: is checked. Save the View.
We have finished desigining our first view.
Create a view controller
Now we need to create a View Controller. View controllers play a very central role in create an iPhone application. They are responsible for managing a view, navigation and memory management. Every view is connected to a view controller. So let us start by creating our view controller. The UIKit provides a class UIViewController which hides most of the default behavior. To create a new View Controller select Xcode then click on classes and select File -> New File and select UIViewControllersubclass, click on Next and name your file "HelloViewController".
Now we have to create variables for the controls we defined in our view. So we can connect these variables to the actual controls on the view. To do this, open the header file and add the following code
Now if you compile your application, it should succeed but with warnings.
You notice that the controls are defined with the IBOutlet keyword, this tells the compiler to make these variables available in the Interface Builder. We also have properties defined for our variables. If a property is defined with the same name as an existing instance variable then then property ends up using that variable internally. The attribute retain while declaring the property tells the compiler to retain the object during assignment.
Event handling
We have also declared a method to handle the button click event. This method is declared with a special keyword called IBAction, which tells the compiler to make this method available in the Interface Builder. The method takes a parameter of type id (generic type) and returns void (denoted by IBAction).
Double click the button and enter "Click ME!!!". This can also be done by selecting the button and changing the Title property in the Attributes Inspector. Select the label and make sure that "Clear Context before Drawing: is checked. Save the View.
We have finished desigining our first view.
Create a view controller
Now we need to create a View Controller. View controllers play a very central role in create an iPhone application. They are responsible for managing a view, navigation and memory management. Every view is connected to a view controller. So let us start by creating our view controller. The UIKit provides a class UIViewController which hides most of the default behavior. To create a new View Controller select Xcode then click on classes and select File -> New File and select UIViewControllersubclass, click on Next and name your file "HelloViewController".
Now we have to create variables for the controls we defined in our view. So we can connect these variables to the actual controls on the view. To do this, open the header file and add the following code
Now if you compile your application, it should succeed but with warnings.You notice that the controls are defined with the IBOutlet keyword, this tells the compiler to make these variables available in the Interface Builder. We also have properties defined for our variables. If a property is defined with the same name as an existing instance variable then then property ends up using that variable internally. The attribute retain while declaring the property tells the compiler to retain the object during assignment.
Event handling
We have also declared a method to handle the button click event. This method is declared with a special keyword called IBAction, which tells the compiler to make this method available in the Interface Builder. The method takes a parameter of type id (generic type) and returns void (denoted by IBAction).
Now we need to implement the method and also synthesize the properties. Basically telling the compiler to create the getter and the setter methods.
Open the implementation file (HelloViewController.m file) and add the following lines after the @implementation HelloViewController line.

Now write the following code to display a message to the user.
The variable sTemp is an object created with the message alloc and initialized with initWithFormat message. As you can see %@ is a place holder in the string for the nth variable position. The logic checks every combination to find out what type of message to display based on the user input. Since the string is an instance of NSString and created using alloc, we have to deallocate it manually. This is done by passing the release message to the receiving object (usually on the left hand side).Also we have three properties to hold the text fileds and the label on the view. Since they are declared with the retain attribute we need to release their memory too. This is done in the dealloc method, as shown below. dealloc method is used to release the memory of the Objective-C objects we create.

Add view to the window
Now, we have to add the view as a sub view to the existing window which shows up in the simulator. To do this open HelloUniverseAppDelegate.h file and create a variable of type HelloViewController and also create a property. Since we are using HelloViewController type in the header file, we have to tell the file about our view controller. We do this by adding a forward declaration, which tells the compiler that the class is defined somewhere else and do not bother looking for it now. Forward Declaration is added before the interface begins using @class classname.
In the implementation file, we need to synthesize the property and also release its memory in the dealloc method.
It is in the applicationDidFinishLaunching method we will add our view as a sub view to the window. This is the method which is called when the application is finished loading and this is where we should set up the initial view the user will see or restore the application.
Add the view as a sub-view to the main window.
- Create an object of type HelloViewController using the alloc message and instantiate using initWithnibName loading the nib file HelloView from the main bundle. A bundle is not relevant to this article, but most of the nib files will be loaded from the main bundle.
- Set the view in the property.
- Release its memory.
- Then we get the view from the view controller and add that view as a sub view to the window. Here the view message is passed to the view controller and the returned view is added as a sub-view to the window.
- Then we make everything visible.
Now we need to connect the controls on the view to the objects we created. To do this double click the HelloView.xib file, which will open the Interface Builder.
We first have to set the view controller to the File's Owner Proxy Object. To do this select the File's Owner and then select Identity Inspector and from the Class drop down select HelloViewController. If we take a second to look at this page, under Class Outlets we will see all of our variables defined in the header file are present here. Now we need to connect the view controller to the view. To do this click on view and select Connections Inspector, here we will see all our variables defined and it will look something like below.
Next to the view you see an empty circle, click the circle and drag it over to the view and release. You will notice that a connection has been made from the view variable to the view. We need to do the same for the variables lblMessage, txtFirstName, txtLastName.When do you that, the connection inspector will look like this
Now we need a connection to invoke our display message method when the button is clicked. To do this select the view and its connection inspector. There will be event called "Touch Up Inside" which is the button click event. Click the empty circle and drag it over to the File's Owner object and when you release it, you will be presented with one option and that is the displayMessage action, select it to create a connection. Your connection should look like something below.
That is all we need to do. Go back to Xcode and click on Build and Go. The application should compile without any errors and no warning messages. Enter your first and last name and click on the button and the message will show up. But we do have a problem, it looks like the text editor does not know that we are done editing and does not close itself. To fix this, we need to implement a protocol in our view controller.The way we implement a protocol is within the <> symbol after the super class name in the interface file. The protocol we need to implement is UITextFieldDelegate. Using this protocol we can set the File's Owner as a delegate from the two text fields. Your interface declaration in the interface file should look something like this
Now we need to implement the method which will handle the closing of the text editor when the done button is clicked.To do this add the following method to your implementation file.
We check from what field this method is being called (as on a view we can have multiple controls) and if it is either the first name text field or the last name text field we will send a resignFirstResponder message and return YES, which is similar to returning bool.Now we have to tell the text field's to use the File's Owner as a delegate. To do this, select the view and click on the first name text field and select the Connections Inspector. We will see a field called delegate, click on the empty circle and drag it over to the File's Owner proxy object and release it and a connection will be created. Do the same for the last name text field.
Save your view and click on Build and Go in Xcode. Now the application performs as expected.
You have now successfully created your first iPhone application. Also included with this article is the source code for the application, this is the same source code I used when writing this application. Click here to download the source code.
Please feel free to let me know your likes and dislikes about the tutorial.
My next tutorial will show you how to use the tab bar, where we will create more then one view.


52 comments:
Nice tutorial!
Thx for your work!
greets from italy
Please keep posting :)
You're the first useful tutorial I have found :)
Thank you for you work in posting this tutorial!
Very helpful :-)
The same here, this is the first tutorial which is up-to-date and good structured... keep posting ;)
thx!!
Good work that may inspire some people to write they own apps, well done.
This is the best tutorial I've read so. It's written in a way a php programer such as my self can understand and follow to learn how to program for the iPhone. Keep up posting!!!
Thanks!
I'm getting 3 errors when I compile:
error: field 'viewcontroller' has incomplete type
error: property 'viewcontroller' with 'retain' attribute must be of object type
confused by earlier errors, bailing out
Hi gishdog
You will get this error if you have missed * before your variable while declaring a property.
So the line should be something like this
@property (nonatomic, retain) UIViewControllerClass *variable.
nonatomic because only a single thread will access this property
retain because we want the property to retain the object during assignment.
Thanks Jai - got it working...
Just added you to my blog - great resource - please keep up the good work.
Any chance you'll get into the interface builder a bit deeper?
Hi nice tutorial thx.. but i get this warning msg which says no initwithNibName:bundle method found
Do you know what that means? I assume it doesnt understand what initWithNibName is.
the text description and the shown pictures dont go hand in hand in some cases - this is a bit confusing.
First of all major kudos!!! Thanks for this its been very educations.
I got all the way thru writing it and get this exception when trying to run:
"HellowView" nib but no view was set
I downloaded your code and could not see any differences between the code xid.
Any suggestions?
This has got me off the ground for how the delegates, controllers, and Interface Builder hang together - I really needed this.
Many thanks for taking the time to do this.
I may have some questions for you :)
These tutorials are very useful. Can you recommend a good book on the interface builder?
Also, I am trying to find a way to append an item number to each cell in a list / table view (as the mail application or the netnewswire app does), e.g.
Inbox (12)
Where '(12)' is right aligned, and in a rounded rect with white on grey background...is this a standard iphone api as various apps seem to do it?
First of all, a HUGE THANKS for an excellent tutorial - the very first useful IB tutorial I've come across.
I wonder if you can help me - every time I press the button, the button turns blue, nothing gets displayed and GDB kicks in with a "Terminating because of an uncaught exception message". I've downloaded your source and it works fine. I've gone over the code, including comparing it to yours several times already and I can't seem to find the bug. I'd appreciate any suggestions you may have...
Hi Tom,
Thanks for your message. Try checking these things
1. In your nib file the File's Owner class is set to your view controller class you created. In my tutorial, this is called "HelloViewController". You do this by double clicking HelloView in resources which will launch the interface builder and select File's Owner and click on Identity Inspector. The Class selected should be the controller class you created.
2. Open the Connections Inspector and you should see a connection from the File's Owner view to the actual view .
3. applicationDidFinishLaunching method should look like this
//Load the view controller from the HelloView nib file.
HelloViewController *vController = [[HelloViewController alloc]
initWithNibName:@"HelloView" bundle:[NSBundle mainBundle]];
//set the view.
self.viewController = vController;
//release the view controller.
[vController release];
//Add the view as a sub view to the window.
//Here we are asking the view controller to get its view and add it as a subview to the window.
[window addSubview:[viewController view]];
// Override point for customization after app launch
[window makeKeyAndVisible];
Let me know if you have any questions.
Hi Chin,
Objective-C is case sensitive. You have 'w' in initwithNibName in smaller case, it should be initWithNibName.
I hope this help.
Thanks,
iPhone SDK Articles
http://www.iphonesdkarticles.com
Hi Frank,
I believe books on iPhone application development are coming out soon. I think you can pre-order it on amazon http://www.amazon.com/iPhone-Open-Application-Development-Applications/dp/0596518552/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1217104533&sr=8-1
If you want to design your table view cell like the mail application, then you need to add a few steps
1. Create a rectangle of some dimensions
2. Create a label out of that rectangle, and set your label properties. Assuming this is the label which shows up on the left side.
3. Give the label a unique tag. Do this by setting the tag property.
4. Add the label as a sub view to the table cell.
5. Initialize another table (one for the right side), set its properties and give this label a unique tag too.
6. Add the label as a sub view to the table cell.
7. Now in cellForRowAtIndexPath, instead of writing to the text of the cell, you will create labels (get the same label from the text) and set the label's text property and return the cell.
I' am in the process of writing an article which shows how to do this.
Thanks,
iPhone SDK Articles
http://www.iPhoneSDKArticles.com
Thanks philip,
You can send your questions to iphonearticles [@] gmail [.] com
It looks like, a connection is missing from the button on the view to a variable in your view controller.
Make sure that
1. You have a variable declared for your button in the view controller.
2. Create a connection from the button to the variable, using Connections Inspector.
3. Create a method handler in your view controller and link up with method defined in the view controller class.
Thanks
very helpful! better than the tutorials from apple
Your line:
@property (nonatomic,retain) HelloViewController viewController;
causes an error and needs to be changed to:
@property (nonatomic,retain) HelloViewController *viewController;
The only thing missing was the *. Other than that, fantastic tutorial.
Nice tutorial, I managed to follow the gist and add some private stuff like a tableview and it works!
BTW,tableview can only handle single columns, anyone can advice how to handle multiple columns and scroll it properly?
Thank in advance,
JT
If there are weird exceptions causing the app to quit, open the debugger. 9 times outta 10, you can probably find the cause there (in my experience as least :)
Thanks for the tutorial. I have a couple of suggestions:
-Make the images full size in the body of the article.
-Have some more screen shots when you're talking about making connections in Interface Builder. I found this section a little bit confusing.
I'm off to read the rest of the articles in the series.
Thanks again!
Hi Stewart,
Thanks for your comment and your time.
I' am thinking about creating video tutorial on how to use the interface builder. I find it hard to write about the Interface Builder, as it is such a visual tool.
Thanks,
iPhone SDK Articles
http://www.iphonesdkarticles.com
great tutorial!!
I had a few issues but Ive been able to find and fix all but one bug:
The text fields seem like they are not accepting the text I type into them. After I enter the text and click the button, the else statement is executed. No matter which text field I use, the same message is always displayed: "Anonymous says Hello Universe!!"
I've gone over the "if else" and "else if" statements and the program runs error and warning free so I don't think it's a code problem. I've compared my HelloView nib with yours and they look the same.
Any ideas?
Great tutorial. First helpful one I've managed to find online yet. Just have a few problems. I ended up with eight errors when launching before adding the protocol. I went through and managed to fix four of them, but four still stop me from launching, all in HelloUniverseAppDelegate.m. There is a "syntax error before 'HelloViewController'" marked on line 1, and the rest seem to be related to viewController. First, 'no declaration of property' on line 4, then "request for member 'viewController' in something not a structure or union" after the line "self.viewController = vController;", and also "'viewController' undeclasred (first use in this function)" after adding the view as a sub view to the window. Any ideas as to what I should check?
In HelloUniverseAppDelegate.m I am getting 3 errors...
"error: 'viewController' undeclared (first use in this function)" at lines 30 and 38
and this after @end...
"error: synthesized property 'viewController' must either be named the same as a compatible ivar or must explicitly name an ivar"
Any idea what might have gone wrong?
To ernest
Hello,
Can you make sure that you have the following line in the header file
HelloViewController *viewController; within braces of the interface, like this
@interface ClassName : NSObject {
HelloViewController *viewController;
}
Thanks,
iPhone SDK Articles
Thanks so much for taking the time and making the effort to create such a helpful tutorial!
Great tutorial! Thnx alot
Great tutorial. I'm going through the entire series you have posted. Good job!
great tutorial, maybe someone can help me with the following
i have a couple of warnings after completing this lovely tutorial.
the two warnings are
warning: incomplete implementation of class 'MyViewController'
warning: method definition for '-displayMessage:' not found
i checked with your source code and it all look the same. i did change the name as you can see. it crashes in the simulator. i think it has something to do with a default view?
warnings are gone, i forgot to connect the textboxes outlet delegate to files owner.
but the app sill quits in the sim, says terminated due to uncaught exception.
remove my last comment, the warnings are not gone.
sorry dude for recalling comments.
Hi Tony,
Can you give me more details on the error. You can send me an email at iphonearticles {@} gmail [.] com.
Thanks,
iPhone SDK Articles
Calvin ,
I had this same problem. Check HelloUniverseAppDelegate.h for errors.
In my case, I had an error on this line:
@class HelloViewController;
got the app to run properly, thanks for the great tutorial. aside from issues getting it to run on my phone.
Your mobile device has encountered an unexpected error (0xE8000001) during the install phase: Verifying application
i cannot seem to get the keyboard to pop up when i click a text box in the sim. (it shows the dial pad) must be something i missed.
Hi, for the step "Connect the controls on the view to the controller objects" I am not seeing HelloViewController as an option in the class drop down. I do see HelloUniverseAppDelegate however.
I've tried going through the tutorial a few times from scratch and still get stuck at this point.
Any ideas or suggestions?
Thanks,
Matt
Hi Matt,
Your XCode project should contain "HelloViewController" class. You can create a new one by following these steps
XCode -> File -> New Class -> Select UIViewController subclass.
Thanks,
iPhone SDK Articles
This is by far the best iPhone tutorial for beginners. It's simple. It does something. And it works!!!
Thanks for starting me on my journey.
Here were the 2 corrections it required for me:
Adding the * before viewController in the @property statement
@property (nonatomic, retain) HelloViewController *viewController;
And case consistency of viewController everywhere.
Good luck everyone !!!
Hi
I am facing the same issue as Matt, where the HelloViewController does not shows as an option of the class drop down. I actually typed in the class name on the box and can see the lblMessage, txtFirstName and txtLastName in the outlets, but can not see the other ones, hence can not drag the view.
By the way, I did created the class HelloViewController on the project as per the instructions, in fact I can see it listed on the classes of the project on xcode.
Not sure what I am doing wrong, your help would be greatly appreciated.
Regards
AVL
Cool !
if i wanted to make pressing the button also returnTextField - so for example if i didn't click Done, i just hit the Click ME!!! button - it would also hide the keypad. what would i need to do ??
thanks for these cool tutorials... i feel like i've actually learnt something today !
previous comment!
nevermind, i figured it out!
i added
[txtFirstName resignFirstResponder];
[txtLastName resignFirstResponder];
to the Action function !
seems to work :)
For those who did not find the HelloViewController in the drop down box, delete your HelloView.xib and recreate it.
You may have noticed along the way that the TextInputTraits section wasn't there.
I'm not sure what caused the error, but this process worked for me.
Vishay (nihalani at berkeley dot edu)
P.S. Thanks for the great tutorial!
Thank you so much. You're missing a '*' next to viewcontroller property line. Other than that, AWESOME write-up!
Better tutorial than the tutorials that were in the book I bought on iPhone OS Development
I am having trouble. Can someone post code that works so I cn see where I went wrong?
Thanks.
Hi,
QQ: can someone explain to me why in the dealloc method of the HelloViewController sFirstName and sLastName are not being released? I would of thought that even with copy their retain count is being increased, no?
Thanks in advance!
To Nils,
Yes sFirstName and sLastName should have been released in the dealloc method.
I will update the code and the screenshot as soon as possible.
Thanks,
iPhone SDK Articles
Thanks for the good work. I'm from the VBA/VB/.NET world. Does anyone know why it takes so many lines of code to accomplish this hello world task while in VB or Java it would only take about one line?
Is there a possibility that Apple will change the language to something a little easier?
Hopefully, I'm just getting over the learning hump and will find the development a lot easier.
Kind comments please.
Post a Comment