iPhone FirstApp: Guess the number - Part 1
Tuesday, June 23, 2009The first source that I passed through the hands was written in Basic and consisted of a few lines of code, for enlightening me. It was a simple game that generates a random number from 1 to 10 and, through keyboard input, make sure the number entered was Maggioni, less than or equal to the random number. Despite its crude simplicity remains, for me, one of the best examples - simple, fun and practical - to explain to anyone who does not know anything about programming actually what is meant by "computer program". So I decided to present it anew for Apple iPhone, maybe help someone ...
In this post we achieve a particular version of "Guess the number" and called FirstApp. Later rewrite the same application with different methods, such as manually creating a UIView or bequests from Interface Builder.
The application already made, if you only want to download, is available on my Google Code repository:
1 - start
Open up Xcode, choose New Project from the File menu and choose, for this version, from classic View-Based Application (the next time we start from Window-Based Application to obtain the exact same result.) Call the project FirstApp and save it where it suits you most.

As you'll notice I'm still using the version of XCode for SDK 2.2.1, because the SDK 3.0 are still "very" stable. Keep in mind this picture because with the new version of XCode Some temples are not just identical and some things will change. However for now you do not have to worry about this unless you were already using the latest release of Xcode.
In this version we'll use Interface Builder then, first of all, we're going to design our user interface. Let us open the Resources folder and double click on FirstAppViewController.xib This file is just in Interface Builder, as the file MainWindow.xib (see also the file extension X I nterface B UILDER).
Any other controller will be placed always in this folder. The remaining folders contain all the other files of our application and, in particular, we work a lot on those in the Classes folder.
Going back to Interface Builder we are facing a blank screen that represents our View the container where the objects are placed UIKit of our user interface. This visual object that we are looking through Interface Builder is connected to the file FirstAppViewController.m (and. H) present in the folder Classes.
In the Library window are all visual components to create standardized interfaces, pleasant and accessible on our Apple iPhone.
These are conveniently sorted by category (see the blue sign on top). For inclusion in our View, simply select the component from fienstra Library and drag it within our window View, where you place it, resize it and configure it at will (all things feasible even by code, as we shall see shortly).
Before going further, if this is your first time working with Interface Builder, enjoy a little 'testing of the various components, and when it gets too much, make sure you get something like the image shown below, or a title made with component UINavigationBar an introductory text UILabel a text field for entering the number to guess UITextField and - finally - a simple button UIButton to see if we have guessed

The approach of the components in Interface Builder is through a particular window always divided into four tabs: attributes, connections, size and identity, a kind of "inspector" of the components. Depending on the selected component the dialog is configured identity with the appropriate characteristics of its component. If we select the UINavigationBar for example, we have all the possible settings for this type of component.

2 - Code
Now that we have established and positioned our visual components for the interface, let's write a little 'code to manipulate them. First of all we open the file FirstAppViewController.he let's become like this:
- / /
- / / FirstAppViewController.h
- / / FirstApp
- / /
- / / Created by Giovambattista Fazioli on 19/06/09.
- / / Copyright Saidmade Ltd. 2009. All rights reserved.
- / /
- # import <UIKit/UIKit.h>
- UIViewController { @ interface FirstAppViewController: UIViewController (
- IBOutlet UITextField * number;
- IBOutlet UIButton * button;
- int numeroACaso;
- )
- controllaNumero; - (IBAction) controllaNumero;
- @ end
Lines 12, 13 and 14 define the "variables" of our Game. The first two are pointers to our graphics included with Interface Builder: the text box and button. IBOutlet davati type, serves to create a link, a reference, to the .xib of Interface Builder. Indeed, if we wanted to create our franchisees components through code, without using Interface Builder, simply remove the IBOutlet as applicable. Line 17, however, defines a method (a message-event) we want to flip when you click the button. In this file. H (header file) we performed only definitions. The implementation of the actual code is in the consideration file. M: FirstAppViewController.m Clicking here you CMD + ALT + UP ARROW is passed alternately from the file. H file. M. We shall therefore edit FirstAppViewController.m First of all delete comments at meotdo viewDidLoad (33 th line around) and let it become:
- / / Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- ) viewDidLoad { - (Void) (viewDidLoad
- ; [Super viewDidLoad];
- arc4random ( ) % 10 ; numeroACaso = 1 + arc4random ()% 10;
- , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso);
- )
viewDidLoad is one of the methods invoked when the application starts. If you want to match a bit 'to the document onload JavaScript or $(document).ready() to jQuery. The lines I added are the 5 and 6. The 5, in particular, creates a random number from 1 to 10! The line number 6, however, is only for debugging and printing on the console generated number. Now write the code (the impementazione) of the method controllaNumero() we defined in the file FirstAppViewController.h
- controllaNumero { - (IBAction) (controllaNumero
- ) ; NSLog (@ "push-button numerical control");
- numero.text integerValue ] ; int numeroInserito = [numero.text integerValue];
- , numeroInserito ) ; NSLog (@ "The number entered is% d", numeroInserito);
- numeroInserito <numeroACaso ) { if (numeroInserito <numeroACaso) (
- ; @ message = "Too low ..."
- ( numeroInserito> numeroACaso ) { ) Else if (numeroInserito> numeroACaso) (
- ; @ message = "Too high ..."
- ( numeroInserito == numeroACaso ) { ) Else if (numeroInserito == numeroACaso) (
- ; message = @ "Bravo, you guessed it;
- arc4random ( ) % 10 ; numeroACaso = 1 + arc4random ()% 10;
- , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso);
- )
- UIAlertView alloc ] initWithTitle : @ "Responso" message : message delegate : nil cancelButtonTitle : @ "OK" otherButtonTitles : nil ] ; UIAlertView * alertMessaggio = [[UIAlertView alloc] initWithTitle: @ "Response" message: message delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil];
- ; [AlertMessaggio show];
- ; [AlertMessaggio release];
- ; numero.text @ = "";
- )
This code, the last one to write before going back to Interface Builder, we can define it as the heart of the system, or better of the game. For it occurs if the number entered in the text UITextField is less than, greater than or equal to the number "thought" from our iPhone. Depending on the outcome shows an alert. Line 2, as always, is only for debug and release on the console a message when clicked. Line 4, however, is interesting, this transforms the textual contents of our text field to an integer number. This is necessary to compare the random number numeroACaso with the number entered by the user. In Objective-C, as in C, there are no implicit type conversions, like other high-level languages that do not support tipizazzione variables in strict sense. In some languages, in fact, you can compare strings and integers without performing any conversion or explicit casting.
Line 5 prepares a pointer to a string message that will contain the answer to display nell'alert. Lines 9 to 17 control the number entered by the user with the random number and draw the necessary conclusions. I purposely inserted these if brutal to make thoroughly clear the code. Alternatively we could use:
- numeroInserito - numeroACaso ) <0 ) ? - 1 : ( ( numeroInserito - numeroACaso ) ? 1 : 0 ) ; int decision = ((numeroInserito - numeroACaso) <0)? - 1: ((numeroInserito - numeroACaso)? 1: 0);
- decisione ) { switch (decision) (
- 1 : homes - 1:
- ; @ message = "Too low ..."
- break;
- : case 1:
- ; @ message = "Too high ..."
- break;
- : case 0:
- ; message = @ "Bravo, you guessed it;
- / / Start again ...
- arc4random ( ) % 10 ; numeroACaso = 1 + arc4random ()% 10;
- , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso);
- break;
- )
We join the queue with Interface Builder
Let us now return to Interface Builder, click the file always FirstAppViewController.xib What we do now allow to link the visual interface made with Interface Builder and the code we've written, especially with components highlighted with IBOutlet The components that we must link our code is the text box and button, as defined in interface definition file FirstAppViewController.h To these we had named respectively numero and bottone From Interface Builder we have various ways to link the visual components with code, one of the simplest is to click with the right mouse button on our visual component, such as text field UITextField

This window is different for each component, shows us all that we can "link" with the code. In particular we are interested in the last entry, the section Referencing Outlets: New Referencing Outlet. Click on the "circle" to the right and - holding down the mouse button - drag the window princiaple FirstAppViewController.xib on the icon FirstAppViewController (File's Owner):

Releasing the mouse button a menu will appear with a list of all the "variables" (properties) IBOutlet and defined as UITextField

In our case we select numero Repeat the exact same procedure for the button, adding that the latter had also defined an event: - (IBAction) controllaNumero; Eventually otteremo:

Conclusions
If you've done everything correctly we're done! Our play is ready. In case you can download the complete source here. Obviously this is just an example and there are some missing details to make it a real application, the 57x57 icons added to the controls on the number and other details yet. The development process described here can be varied, for example via Interface Builder once, ie at the end: before you write all the code and then you go about Interface Builder to link the objects. In this example we have moved quickly on Interface Builder to design the outline of our interface, since the application simple.
Next time we'll see how to implement the medisimo "play" without using Interface Builder.













There are no comments for this post
Leave a comment