Hello World

April 25th, 2009 by Chris Leave a reply »

Hello World – usually the first program every programmer, no matter in what programming language, creates. It’s very simple and a great example if I present it to you step by step.

Let’s start by opening Xcode. Close any welcome windows which may appear. Choose File => New Project.

xcode_template

Make sure the Application from iPhone OS category is selected on the left and choose Window-Based Application and press Choose… . [ Window-Based Application is the simplest template you can choose to begin, other are more complex but can save your time if they suit your application ]. Save your project wherever you like and name it properly for example HelloWorld.

helloworld_start

Xcode created some main files already for you. These files are categorized into 5 groups:

  • Classes – where HelloWorldAppDelegate.h (header) and .m (implementation) are. In header file you have declaration of the class, it’s objects, frameworks and other files inclusion. In implementation file you have class methods.
  • Other SourcesHelloWorld_Prefix.pch is the prefix header for all other source files within your project, so if in future you need to import the same file to all other classes you can use this file instead of modifying each of the classes. main.m is the standard main() function known from C language that is called first.
  • ResourcesMainWindow.xib is called NIB file (like other with .xib extension) to create user interface with Interface Builder. Info.plist is the configuration file, where you can change some project settings – Bundle name and so on.
  • Frameworks – source files created by Apple providing you basic and major functionality.
  • Products – compiled project goes there

Sounds difficult? I don’t think so. You can organize you files in a way that suits you. You will modify only files from Classes and create other classes.

To create the simplest Hello World example we could just edit a MainWindow.xib with Interface Builder but you wouldn’t learn anything at all. We are going to create your own view (iPhone application consists of only one window any many views displayed in window) and its view controller.

In Xcode choose File => New File and from Cocoa Touch Classes select UIViewController subclass, Next. Enter MyView.m, as file name, and without changing anything else press Finish.

viewcontrollernewfileviewcontr

Now let’s create a view, where the text will be displayed. Choose File => New File and from User Interfaces choose View XIB, Next, call it MyView.xib, Finish.

Double click MyView.xib and it will be opened in Interface Builder.

interfacebuildermainview

As you see MyView.xib currently consist of three objects. File’s Owner – there we will assign our MyView class soon, First Responder – handler of touches, buttons pressing, entering data, and View the part that in next few minutes will be visible on simulator screen.

In Interface Builder go to Tools => Library. Find on the list Label (UILabel) and drag and drop it on the View. Click on the label and resize it. Double click and change it text to Hello World. You can also go to Tools => Inspector and change it aligment, color, shadow – it’s up to you, don’t close the Inspector window.

Now select File’s Owner and go to the last tab in Inspector (Object Identity). View won’t be shown by itself that is why we already prepared the MyView class that’s going to control the view; under Class Identity in Inspector enter MyView as Class. As you see auto-completion works great (also in Xcode) so just entering m refers to MyView. Now File’s Owner is a type of MyView, not NSObject any longer. That’s not all. One .xib file may consists of many views and even if you have only one right now, you have to set is as a main view of MyView class. Again in File’s Owner’s Inspector in second tab (MyView connections) you have 3 outlets, one of them is called view.

interfacebuildernoconnection

Click on the circle that’s on the right next to view hold your mouse button and drop it on the View window or View from MyView.xib window. The connection is set. While using an Interface Builder you have no options to give a unique names of objects like views, labels, switches, buttons or any other part of the interface. You have to prepare them in your class files like MyView.h and .m, and later you connect them just like before. Because MyView class is a UIViewController it already expects a view you can create programmaticaly or using Interface Builder.

interfacemyviewconnections

Let’s choose File => Save and go back to Xcode. Now we have to create some code. MyView class is already prepared to display Hello World, but we have nowhere entered any information to call this class. Let’s fix it.

Go to HelloWorldAppDelegate.h and under:

#import <UIKit/UIKit.h>

enter:

#import "MyView.h"
@class MyView;

These two lines of code allows you to use MyView class within HelloWorldAppDelegate.h and .h – files that are called when the application start. Let’s now go to the implementation file – HelloWorldAppDelegate.m and in the applicationDidFinishLaunching method enter these two lines:

MyView *viewController = [[MyView alloc] initWithNibName:@"MyView" bundle:[NSBundle mainBundle]];
[window addSubview:[viewController view]];

it should look like below:

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	MyView *viewController = [[MyView alloc] initWithNibName:@"MyView" bundle:[NSBundle mainBundle]];
	[window addSubview:[viewController view]];
   	// Override point for customization after application launch
	[window makeKeyAndVisible];
}

First line creates the new MyView objects, we will use only one instance of it, but in some cases we can create (alloc) more objects from the same class. The second file put the MyView class view on the application window, in other words the view is a subview of a window. Everything what is part of the interface is a kind of view. The label with HelloWorld is a subview of MyView’s view.

That’s all. Let’s press Build & Run. In the iPhone Simulator we should see our application.

helloworldsimulator

That was to simple, wasn’t it? So, I would like to show you how to handle actions, like pressing a button. When the button is pressed the label shows Hello Universe.

Let’s go to the MyView.h and between { and } let’s add an label outlet and before @end an action. The outlet looks like: IBOutlet UILabel *myText that’s mean that my name of the object is myText of type UILabel, IBOutlet keyword means that it’s visible in Interface Builder. The action looks like -(IBAction)changeText; – I declare an action – method named changeText which will be visible in Interface Builder because of IBAction keyword. If you compile (Build) your project now, you will get two warnings, because in header file you declare the changeText but in implementation file doesn’t provide any code what this method does.

MyView.h should look like:

#import <UIKit/UIKit.h>
@interface MyView : UIViewController {
	IBOutlet UILabel *myText;
}
-(IBAction)changeText;
@end

Now we have to implement changeText method in MyView.m file. Add this code below @implementation MyView:

-(IBAction)changeText {
	myText.text = [NSString stringWithFormat:@"Hello Universe"];
}

As you see, we change the text of the label by using it’s name myText and and text keyword – property with dot between them, why not only myText? That’s because myText is the bigger object not only a text placeholder, you can easily change it’s background colour, font, opacity, shadows, just like you could in Interface Builder.

Build your project, it’s everything from the code site, now we have to go back to improve an interface. If you have already quited Interface Builder double click MyView.xib to reopen it. From the library, select Round Rect Button (UIButton) and drag’n'drop it to the view. Just like with the label you can double click on it and enter some text, for example Change Text. Let’s go to the File’s Owner Connections Inspector and you should see MyText as one of the outlets, and changeText as one of the actions:

connections

Just in the same way you connected view outlet to your view, connect myText to the label – click on the circle next to myText and release your button on the Hello World label. Although it’s only one label on the view, you are doing it to show the compiler what/where is the label called myText. Now let’s connect an action with the button. Click on the circle next to changeText and release your mouse button on the Change Text button. The menu should appear.

buttonactions

As you see there are few predicted user behaviours how he can press the button. We are interested in Touch Up Inside – it will call the changeText method when user press and release his finger without draging it out from the button. Now, MyView Connections should look like:

connectionsall

Save MyView.xib and press Build and Go. Now pressing the Change Text button changes the label’s text from Hello World to Hello Universe. Pressing the button again calls the changeText method but there is no change visual to us. It’s almost all but we forgot about one thing, so called Memory Management. We declared myText outlet and it will stay in memory until user reboot the device. You need to fix it – go to the dealloc method in MyView.m (should be on the bottom) and add a line [myText release];.

- (void)dealloc {
    [super dealloc];
    [myText release];
}

That’s all. Hello World is something you should do all by yourself from now. I tried to show you everything as simple as possible. In next examples I will not tell you everything so detailed and post screenshots for every single step.

xcodeprojDownload the project

Advertisement

27 comments

  1. 1. Hi there, just became aware of your blog through Google, and found that it is really informative. I am gonna watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

    2. It is perfect time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I wish to suggest you some interesting things or suggestions. Maybe you can write next articles referring to this article. I wish to read even more things about it!

    3. Excellent post. I was checking constantly this blog and I’m impressed! Very useful info particularly the last part :) I care for such info a lot. I was seeking this particular info for a very long time. Thank you and best of luck.

    4. hey there and thank you for your information � I�ve certainly picked up anything new from right here. I did however expertise a few technical points using this website, as I experienced to reload the site lots of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I am complaining, but slow loading instances times will sometimes affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Anyway I�m adding this RSS to my e-mail and can look out for much more of your respective intriguing content. Ensure that you update this again soon..

    5. Excellent goods from you, man. I have understand your stuff previous to and you’re just extremely great. I actually like what you have acquired here, really like what you’re saying and the way in which you say it. You make it enjoyable and you still take care of to keep it smart. I can’t wait to read far more from you. This is actually a wonderful site.

    6. Pretty nice post. I just stumbled upon your blog and wished to say that I have really enjoyed browsing your blog posts. After all I�ll be subscribing to your rss feed and I hope you write again very soon!

    7. I like the helpful information you provide in your articles. I will bookmark your weblog and check again here regularly. I am quite certain I will learn a lot of new stuff right here! Best of luck for the next!

    8. I think this is among the most important information for me. And i am glad reading your article. But should remark on few general things, The web site style is ideal, the articles is really excellent : D. Good job, cheers

    9. We’re a group of volunteers and opening a new scheme in our community. Your site provided us with valuable information to work on. You’ve done an impressive job and our entire community will be thankful to you.

    10. Unquestionably believe that which you said. Your favorite justification appeared to be on the net the simplest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thanks

    11. This is very interesting, You’re a very skilled blogger. I have joined your rss feed and look forward to seeking more of your excellent post. Also, I have shared your site in my social networks!

    12. Hey There. I found your blog using msn. This is a very well written article. I�ll be sure to bookmark it and return to read more of your useful info. Thanks for the post. I�ll certainly return.

    13. I loved as much as you will receive carried out right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get got an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.

    14. Hi, i think that i saw you visited my blog thus i came to �return the favor�.I am attempting to find things to improve my web site!I suppose its ok to use a few of your ideas!!

    15. Just wish to say your article is as surprising. The clarity in your post is simply spectacular and i could assume you are an expert on this subject. Fine with your permission let me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please continue the gratifying work.

    16. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but instead of that, this is fantastic blog. A great read. I’ll certainly be back.

    17. Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how can we communicate?

    18. Hello there, You’ve done a fantastic job. I will definitely digg it and personally recommend to my friends. I’m confident they will be benefited from this website.

    19. Excellent beat ! I wish to apprentice while you amend your website, how can i subscribe for a blog site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept

    20. I am extremely impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Anyway keep up the nice quality writing, it�s rare to see a great blog like this one today..

    21. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I�ll be subscribing to your feeds and even I achievement you access consistently rapidly.

    22. My brother recommended I might like this blog. He was totally right. This post actually made my day. You cann’t imagine just how much time I had spent for this info! Thanks!

    23. I do not even know how I ended up here, but I thought this post was great. I do not know who you are but certainly you are going to a famous blogger if you aren’t already ;) Cheers!

    24. Heya i�m for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you aided me.
    25. I was recommended this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You are wonderful! Thanks!

    26. Excellent blog here! Also your site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my website loaded up as fast as yours lol

    27. Wow, incredible blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!
    28. I am not sure where you are getting your information, but great topic. I needs to spend some time learning much more or understanding more. Thanks for excellent information I was looking for this information for my mission.

    29. You actually make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I�ll try to get the hang of it!

    30. I have been browsing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the net will be a lot more useful than ever before.

  2. thanks says:

    thanks bud. the impact of tutorials like the are unseen but you can be sure they are changin lives. one day I will be a complete programmer and teach others the same. self sustainability on something as seemingly insignificant as linesof code is wonderful. thanks again for the concise breakdown….very understandable for novices like myself

  3. porn watch says:

    teen porn watch şş

  4. Have you ever tried twitterfeed within your blog, it might possibly be cool

  5. I know where the images from the blog posts are, but don’t know where to look for the blog posts in my backups. Can you help? Hope it’s not a silly question..

  6. Cami says:

    hello Chris! all people already says you but once again thank you men!

  7. Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Natually I’ll give you a link on your web blog. Thanks for sharing.

  8. Lay says:

    Hi,

    Thanks for doing this post, wonderful explanation.

  9. Vito Perkiss says:

    There are numerous blogposts available close to this particular, There’s no doubt that choosing now there reference point could experience decided to get this identify or post truly useful. Useful mission expression this post is unsafe. Basically I need to pronounce the advice given at this point seemed to be one of a kind, basically repair even more all-around finish, aiding together with other ex – data have already been essentially very good. The actual items you’ll like touched allow me to share crucial, hence I actually most definitely can area several of the details the following to develop this in reality great for wholly the particular newbie’s at this point. Thanks a lot this info. Essentially beneficial!

  10. John Wars says:

    You need more explanation more photos and vedieo but your eziene is so good Thanks John Wars ,,,

  11. Hi, cheers for the demo. I did one using the view-based app template. This gave me some more building blocks in creating and using my own views as sub views to the main window. Very very useful, thanks.

  12. Nice info, give thanks to the publisher. It is incomprehensive in my experience now, however in common, the usefulness and importance is overwhelming. Regards and all the best …

  13. mikje says:

    after compiling i get a white screen, i think because there are 2 nib files, and MainWindow is used but nowhere modified.

  14. I need to many thanks for the endeavours you have obtained contributed in composing this blogpost. i am hoping the identical top-quality publish from you from the lasting as well. In simple fact your soil breaking composing skills has inspired me to start my very own web page now. in real truth the blogging and site-building is spreading its wings rapidly. Your create up may likely be considered a very good design of it.

  15. Whether it truly is or maybe definitely not, best of luck finding out!

  16. Lach says:

    Hi Chris,

    Thanks for the iPhone Hello World tutorial. Great introduction to iPhone development. Much better than the other materials I found. Just a slight confusion on the object deallocation… I thought that Objective-C 2 added automatic memory management. Is that not the case for iPhone apps? How come you have to manually deallocate the object?

    Cheers,
    Lach

  17. piano tutor says:

    This post was very nicely written, and it also contains a lot of useful facts. I appreciated your professional way of writing this post. Thanks, you have made it very easy for me to understand.

  18. Dan says:

    I just wanted to say thank you… You had an improbably small insignificant piece of code that lead me to answering a problem I’ve been having, so thank you again…

  19. I’m a big lover! Thanks for writing this

  20. Casino News says:

    Being a complete newbie, all I can say is thanks for sharing this.

  21. Guido says:

    Thanks for this easy tutorial. The UI tools are really cool..

Leave a Reply