Posts Tagged ‘lesson’

Hello World

April 25th, 2009

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