Category Archives: Xcode

iOS Style Passcode Screen

Today I was asked to create an interface for one of our clients apps, which would allow the user to login to the app by way of entering a pin code. As this app is for iOS it was decided to create the interface to look similar to that found on iOS 7 devices. Here I will show you how I created the interface, along with the code behind checking the pin code entered.

To begin with I created a Single View project in Xcode, and built the following user interface in the Storyboard:
pin-code-screenshot
The interface consists of eleven UIButtons (one for each of the numbers, and one for the Delete), a UILabel with the text set to Enter Pincode, and a UIView with four smaller UIView’s inside which sits under the Enter Pincode label.

Next I gave each of the number buttons a unique Tag, starting at 10 for the 1 button, up to 100 for the 0 button, and each of the four UIViews inside the UIView below the Enter Pincode label a unique tag from 1 to 4 (all will become clear later).

With the interface almost complete we can go to the ViewController.m file associated with the main view in the Storyboard and start writing some code. First we need to create an IBOutlet for the UIView which contains the four small UIViews under the Enter Pincode label, along with four instance variables:

@interface DDViewController ()
{
    IBOutlet UIView *_pinDotsView;
 
    NSInteger _buttonsPressedCount;
    NSInteger _failedAttempts;
    NSMutableString *_enteredPinCode;
    NSString *_pinCode;
}
 
@end

Make sure you change DDViewController for whatever your class is called. First we have the IBOutlet for the UIView containing the four small views, two NSIntegers which will keep track of how many numbers have been tapped on, as well as how many failed attempts the user has made. Finally there is a NSMutableString which will be appended to each time a number button is tapped and a NSString which will hold the pin code to check against once four numbers have been entered. Of course, in the live version we will be using the Keychain to store a hashed version of the pin code, however for demonstration purposes this is good enough. Before we write any more we must hook up the IBOutlet for _pinDotsView to its associated view in the storyboard. I will assume you know how to do this, so lets write more code.

First in the viewDidLoad: method we will give the number buttons a border and change their look from a square to a circle, and the same for the four UIViews inside _pinDotsView. The reason why we gave the UIViews and UIButtons tags will now become clear:

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    for (NSInteger tag = 1; tag <= 4; tag += 1)
    {
        UIView *view = [_pinDotsView viewWithTag:tag];
        [view setBackgroundColor:[UIColor clearColor]];
        [[view layer] setBorderColor:[UIColor whiteColor].CGColor];
        [[view layer] setBorderWidth:1.0f];
        CGFloat radius = view.frame.size.width / 2;
        [[view layer] setCornerRadius:radius];
    }
 
    for (NSInteger tag = 10; tag <= 100; tag += 10)
    {
        UIButton *button = (UIButton *)[[self view] viewWithTag:tag];
        [[button layer] setBorderColor:[UIColor whiteColor].CGColor];
        [[button layer] setBorderWidth:1.5f];
        CGFloat radius = button.frame.size.width / 2;
        [[button layer] setCornerRadius:radius];
    }
 
    _enteredPinCode = [[NSMutableString alloc] init];
    _pinCode = @"5793";
}

Here we use two for loops, one which iterates from 1 to 4 and changes the background of the views to clear, sets their border colour to white, and border width to 1. We then create a CGFloat variable which is given the value that is half the width of the UIView (make sure they are square in the storyboard), then set their cornerRadius property to this value which makes their border into a circle shape. We then do similar to the nine number buttons, and finally initialise the _enteredPinCode instance variable, along with giving the _pinCode a value which will be the number the user is required to input before continuing with the app.

At this point you can run the app to check that this has worked, and hopefully you should see something similar to:
pin-code-final-iinterface
Next we need to create two IBAction methods, one which will be sent a message to when one of the number buttons is tapped, and one which will be sent a message when the Delete button is tapped on. First we have pinButtonTapped: which you need to hook up to each of the number buttons:

- (IBAction)pinButtonTapped:(id)sender
{
    _buttonsPressedCount ++;
    [_enteredPinCode appendString:[sender currentTitle]];
 
    UIView *pinDotView = [_pinDotsView viewWithTag:_buttonsPressedCount];
    [pinDotView setBackgroundColor:[UIColor whiteColor]];
 
    if (_buttonsPressedCount == 4)
    {
        [self checkPinCode];
    }
}

Each time one of the number buttons is tapped on we increase the _buttonsPressedCount variable by 1. We then grab the title label of the button tapped by using the currentTitle property of the UIButton. Using the _buttonsPressedCount variable we can then grab hold of the correct UIView inside _pinDotsView and set is background to white, showing the user they have tapped on x amount of buttons. Finally we check if the user has tapped on four buttons (or whatever you wish to set that to), and if so send a message to run a method called checkPinCode:. Of course you could include the logic inside this if statement, however I prefer to break my code up into smaller pieces which keeps things cleaner, and also separates certain login into their own method. Next up we have the delete: method which you need to hook up to the delete button:

- (IBAction)delete:(id)sender
{
    if ([_enteredPinCode length] > 0)
    {
        UIView *pinDotView = [_pinDotsView viewWithTag:_buttonsPressedCount];
        [pinDotView setBackgroundColor:[UIColor clearColor]];
 
        NSRange range;
        range.location = _buttonsPressedCount - 1;
        range.length = 1;
        [_enteredPinCode deleteCharactersInRange:range];
        _buttonsPressedCount -= 1;
    }
}

Here we are doing the opposite of what the pinButtonTapped: methods does. First we get hold of the correct UIView inside _pinDotsView and change its background colour to clear, remove the last entered number from the end of the _enteredPinCode mutable string, then decrease _buttonsPressedCount by 1.

Now on to the checkPinCode: methods which I mentioned earlier, which as its name suggests will check the pin code entered against that stored in the _pinCode variable:

- (void)checkPinCode
{
    if ([_enteredPinCode isEqualToString:_pinCode])
    {
        [[[UIAlertView alloc] initWithTitle:@"Correct Pin Entered" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
        _failedAttempts = 0;
        [_enteredPinCode setString:@""];
    }
    else
    {
        _failedAttempts ++;
        [_enteredPinCode setString:@""];
 
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
 
        [self animatePinDotsView];
 
        if (_failedAttempts == MAX_FAILED_ATTEMPTS)
        {
            [[[UIAlertView alloc] initWithTitle:@"5 failed attempts" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
 
            for (NSInteger tag = 10; tag <= 100; tag += 10)
            {
                UIButton *button = (UIButton *)[[self view] viewWithTag:tag];
                [button setUserInteractionEnabled:NO];
            }
        }
 
    }
 
    [self performSelector:@selector(updatePinDotsView) withObject:nil afterDelay:0.5];
 
    _buttonsPressedCount = 0;
}

First we check if what the user has entered (which is stored in _enteredPinCode) matches that stored in _pinCode. If it does then we display a UIAlertView informing the user they have entered the correct pin code (for demonstration purposes only), set _failedAttempts to 0, and empty _enteredPinCode.

If the user has entered an incorrect pin code then we enter the else part of the statement. Here we increase the _failedAttempts variable by 1, empty _enteredPinCode and send a message to a method called animatePinDotsView: which will shake _pinDotsView side to side similar to that on an iOS device. We then check if the user has made five failed attempts to enter their pin code. If so we display a UIAlertView informing them of this, and set the userInteractionEnabled property of the buttons to NO which means they cannot make any further attempts. Of course in the live project you will need to do extra work here like setting userInteractionEnabled to YES after 10 minutes.

We then send a message to a method called updatePinDotsView: which will set the background colours of the four UIViews inside _pinDotsView to clear. The reason for using performSelector:withObject:afterDelay: is because we want to see the background of the fourth dot change to white before setting them all to clear. Finally we reset _buttonsPressedCount to 0. The final two methods require are updatePinDotsView: and animatePinDotsView:

- (void)updatePinDotsView
{
    for (NSInteger tag = 1; tag <= 4; tag += 1)
    {
        UIView *view = [_pinDotsView viewWithTag:tag];
        [view setBackgroundColor:[UIColor clearColor]];
    }
}
 
- (void)animatePinDotsView
{
    CABasicAnimation *animation =
    [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setDuration:0.05];
    [animation setRepeatCount:3];
    [animation setAutoreverses:YES];
    [animation setFromValue:[NSValue valueWithCGPoint:
                             CGPointMake([_pinDotsView center].x - 15.0f, [_pinDotsView center].y)]];
    [animation setToValue:[NSValue valueWithCGPoint:
                           CGPointMake([_pinDotsView center].x + 15.0f, [_pinDotsView center].y)]];
    [[_pinDotsView layer] addAnimation:animation forKey:@"position"];
}

The updatePinDotsView: method simply resets the background to the four UIViews inside _pinDotsView to clear. The animatePinDotsView: method used CABasicAnimation to move _pinDotsView side to side three times over a period of half a second. You now have a starter project for allowing users access to an app via a pin code.

My Second App

First I would like to apologise for not posting within the last month. I started my second year of University at the start of October, so unfortunately that has been taking up the majority of my time, allowing next to no time to concentrate on increasing my knowledge of iOS/Objective-C Programming.

Talking of increasing my knowledge of Objective-C Programming, yesterday I received my copy of Objective-C Programming, The Big Nerd Ranch Guide by Aaron Hillegass. Although I have a copy of Steven Kockan’s Programming in Objective-C there are some areas I had trouble completely getting my head around so am hoping this new title will help to fill in the blanks, especially as it comes from the same place as iOS Programming, The Big Nerd Ranch Guide, a book which I call my bible.

Back to the main topic of this post “My Second App”. Yesterday I received confirmation from Apple that my second app Heating Oil Mobile has been approved. Heating Oil Mobile was the brainchild of Matthew Dunne, a fellow student from University who also runs his own web development company. One of his clients is a local oil company, and he had the idea of developing an iPhone app whereby the user could receive up to date quotes for heating oil, and as he does not know iOS Programming (for now anyway) he made the proposal that I do the iOS programming and he would do the back end/server side programming (PHP/client log in area). Basically what happens is that the user inputs their postcode, selects a fuel type and amount of litres to get a quote on, and when they tap on the “Get Quote” button the app sends a PHP request which returns data in the form of XML that is then parsed and presented back to the user on screen.

The parsing of the XML was made very simple thanks to the work of Matt Gallagher at Cocoa With Love, who has created a XML parser which you can download.

Although not a large app I had to overcome some issues with regards to the user experience. Initially we had two screens for the quote, with the first screen having a UIPickerView in it along with the postcode UITextField and “Get Quote” button, which would present a UIModalView that displayed the quote details. The first version wasn’t the best looking of UI’s, and I always wanted everything to be on one screen with the UIPickerView being displayed in a UIActionSheet. Being something beyond my knowledge levels at the moment I found the answer thanks to Tim Cinel.

I also needed to figure out how to move the “Enter Your Email Address” UITextField up automatically (to avoid the keyboard) when the user taps on it. In the end this was straight forward as the objects were in a UIScrollView so I used the setContentOffset: method which is part of the UIScrollView class and looks something like [scrollView setContentOffset:CGPointMake(0, 190) animated:YES]; (which tells the contents of the UIScrollView to move up 190 points).

The app will be available from December 1 2011 and the meantime we hope to get more oil companies on board so that we can reach as many people in the UK with this app. Below are some screenshots from the app.

Heating Oil Mobile App Screenshot 1

Heating Oil Mobile App Screenshot 1

Heating Oil Mobile App Screenshot 2

Heating Oil Mobile App Screenshot 4

Advice For Newbies

It seems a bit strange that I should be writing a post titled “Advice For Newbies”, seeing as I consider myself very much a newbie. I decided to write this as I have received emails from people asking for general advice on learning iOS Development, through to topics such as “how long does it take to learn Objective-C” and “should I be expected to remember everything”. It is quite flattering to be asked these questions, so I decided to share my answers here.

What I wish to share in this post is from my own personal experience of learning Objective-C, the foundation framework and other aspects of iOS Development, (all of which I have simply scratched the surface). This is also the intention of my blog – to share with other people out there some of the aspects I have learned.

Where do I start?
I guess the first thing I would recommend, and something that really is quite obvious is to learn as much Objective-C as you can to begin with. With this knowledge you can move on to learning more about Xcode, and the other aspects of iOS Development.

Printed Matter
When I first started out I purchased Learning iPhone Programming by Alasdair Allan. Like the majority of other iOS programming books out there, it will not teach you Objective-C. It did however give me an initial insight to what I was getting into (or at least so I thought).

I then purchased the third and latest edition of Programming in Objective-C by Stephen Kochan, one of the most recommended titles on Objective-C available. I worked my way through as much of this as possible until the much awaited iOS Programming: The Big Nerd Ranch was published.

As I started working my way through iOS Programming I was initially confused as I thought I already had some knowledge from reading Learning iPhone Programming. This was not quite the case as iOS Programming is based on the Big Nerd Ranch’s iOS Bootcamp course and teaches you initially how to develop view controllers programmatically rather than doing everything in interface builder as Learning iPhone Programming does. The reason I mention this is that I now have a better understanding of how view controllers work thanks to the guys at Big Nerd Ranch.

Here in lies a potential problem with people starting to learn iOS development: There are so many books available on this subject it is hard to decide which ones to read. The two main books I have mentioned here are what I have personally gained from, and there is a third title I have started reading which is Programming iOS 4 by Matt Neuburg.

Another problem you may find is that you are using say Xcode 4.0/4.1, whereas the book you have shows you how to do things using Xcode 3.0. This is not a major problem, however it may through you initially, so stick with it and you will work it out. Then there is Xcode 4.2 which will probably be released to non paid up developers in the next couple of months so if you download this you may have to wait some time for the latest books to be published.

As well as these books, there are also numerous documents available on the Apple Developer website, and you may be able to learn most of what you need directly from here.

Visual Matter
There are also plenty of visual material available on iOS development, from Stanford Universities Developing Apps for iOS (available on iTunesU), through to webcasts and DVD’s available from the likes of Stephen Kochan at ClassroomM.

How long does it take to learn Objective-C?
This is something that one cannot answer as everyone learns at a different pace, and can commit to x amount of hours to learning due to family and other commitments. I have spent this summer learning as much as I can before I return to University at the start of October, so have devoted quite a bit of the last four months to this. Hopefully on my return to University I will be able to commit to at least one (preferably two) days a week to continuing my learning in this area.

Should I be expected to remember everything?
I would say the answer to this is “NO”. Yes, the more you continue to work on your own apps, the more your knowledge will increase, however cocoa touch, the foundation framework and the other frameworks that contribute to iOS development are so huge that I believe that one cannot be expected to remember everything. This is why there is the Apple documentation available through Xcode.

Developing your first app
It may be so tempting to just go ahead and code/design your first app without giving it a thought, however I would highly recommend that you read the iOS Human Interface Guidelines available through the Apple Developer website. This could potentially be a lifesaver as you may use an Apple UI object inappropriately which in turn could lead to your app being rejected. Then there is the various icons you have to supply and their naming conventions as well as having a website for your app. Information on these matters are available in the iTunesConnect Developer Guide which you can download from iTunesConnect.

I hope this has helped in some way, and should you wish to ask anything not covered here then please feel free to get in touch.

My First App

After working through most of iOS Programming: The Big Nerd Ranch Guide, I have been working on my first “proper” iPhone App for the last couple of weeks now. I decided to develop an app that wasn’t too complicated to begin with, and one that I would use myself – something I feel that is important when you are starting out.

As a keen cyclist I will probably be spending more time on my turbo trainer doing shorter sessions, what with going back to University soon, and winter being just around the corner again. These shorter sessions involve doing high intensity interval training where after a warm up of five minutes or so you then work as hard as you can for a short period of time (say 30 to 60 seconds), followed by a rest period of (20 to 120 seconds). These two sessions are repeated a certain amount of times, and are followed by a cool down session of five minutes or so.

With this I have decided to make an app where I could set these times and intervals and be alerted by a bell or other sound when each interval had finished. As it will be run on my iPhone I have also decided to add functionality where I can select music from the iPod to play along with my workout.

I am nearly at a point where I can submit something to Apple to see if it will be accepted into the App Store, however now realise that there are also pieces of functionality that could be added to make the app a better experience for the user, like selecting music for each of the warm up, interval, and cool down sessions, and saving workouts for future use.

So, now I am wondering – should I submit what I have to the App Store and see if it is accepted, and make it better with future versions, or work on making a better app first time round. My head says submit now to see if what I have is not a completely rubbish app and is rejected, whereas my heart says work on it further even if it means starting from scratch again.

Below are some screenshots from the app as it stands now, and I will keep you posted with my submission decision. Of course, I am happy to hear any comments on the screenshots.
Screenshot from my app

Screenshot from my app

Screenshot from my app

Screenshot from my app

Hooking Up Outlets And Actions – An Easier Way

I have been quiet the last couple of weeks as I have been working my way through iOS Programming: The Big Nerd Ranch Guide.

Before starting this book, when hooking up outlets and actions I would go to the relevant .h file and write the code for the outlets and actions, go to the corresponding XIB file and place my text fields, buttons etc…, then hook them up. Through reading this book I have now found a new way of hooking up outlets and actions directly from the XIB file.

For this example I have created a view based project called “Test” and placed some labels, text fields and a button onto the TestViewController.xib file:

Now, staying in the XIB file, Option-Click on the TestViewController.h file. This will bring up the assistant editor, displaying the @interface file, alongside the XIB file:

Control-Drag from the first text field to the instance variable part of the .h file:

When you release the mouse and keyboard you will get the following popup window. In the “Name” box insert the name of the variable – here I have called it nameField:

When you click on “Connect”, an IBOutlet of UITextField type will be placed into the .h file:

Now do the same for the rest of your outlets. For the action, Control-Drag from the button to the method declaration part of the .h file:

In the popup window change the “Connection” to Action and insert a “Name” – here I have called it done:

When you click on “Connect” an IBAction statement will be placed into your .h file, and it should now look something like this with all of your outlets and actions in place:

What will also happen is that the IBAction method will be placed into the TestViewController.m file, along with the relevant release messages in the viewDidUnload: and dealloc: methods:

The iOS Programming book is based on Xcode 4, and I am using Xcode 4.1. I believe that earlier versions use a separate application for Interface Builder, and therefore this will probably not work.

Receiving Accelerometer Data

Following a previous blog post on Changing An Image Programmatically, I received a request asking if I could do a post on how to receive the data from the iPhone’s accelerometer. So on that, here I will walk through a very simple app which will show the data received from the X, Y, and Z axes of the device. Note that this app will not work on the Xcode simulator, so you will need to be a paid up developer to test it on your device.

First we will create a new View Based project and call it Accelerometer. Click on the AccelerometerViewController.h and change to the following:
Here we want to declare the view controller as being the delegate for the accelerometer, meaning that we will implement the method(s) for the accelerometer . We also need to set up three instance variable label outlets and one for our accelerometer.

Now we need to add some objects to the user interface, so click on the AccelerometerViewController.xib to open the user interface view. Drag three labels onto the view, changing the “Label” to X, Y, and Z respectively. Then drag another three labels, and arrange them something similar to:

Here I have changed the background colour of the second lot of labels for viewing purposes only. I also changed the names of these labels to xLabel, yLabel, and zLabel, as you can see in the image above (under Objects/View).

Now we need to hook up xLabel, yLabel, and zLabel to the outlets we declared in AccelerometerViewController.h. Right click on File’s Owner, and click and drag from xLabel to the label on the view as:

and repeat for yLabel, and zLabel.

We can now finish off by updating our code in AccelerometerViewController.m. First we will amend the viewDidLoad method to:

Here we are setting up our accelerometer, telling it to update every 1/10th of a second, and that AccelerometerViewController is the delegate.

When you declare delegates you will need to find out the possible methods that you can use, and some may be flagged as being required. The easy way to do this is by going back to AccelerometerViewController.h, hovering over UIAccelerometerDelegate, and pressing the ALT key and clicking with your mouse/trackpad. This will bring up a window like:

Click on the UIAccelerometerDelegate Protocol Reference link which will bring up the Documentation of Xcode’s Organizer:

You will notice that there is only one method available to implement –accelerometer:didAccelerate: To make life easier you can copy method names from the documentation and past them into your code, so highlight -(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration under methods, return to your project, and past it in to AccelerometerViewController.m. Amend this method to:

Here we are simply saying that xLabel, yLabel, and zLabel.text is what is returned by the acceleration of the device when you move it on its axes.

Finally we need to do some memory management, so amend the dealloc method to:

Now we are finished, you can build and run the app on your device, and hopefully you will see something like:

Hello World – A simple first project

Here I am going to lead you through the steps of creating your first basic project in Xcode. I will provide screen shots to go with my text which will hopefully make it easy for you to follow along.

So fire up Xcode and lets get going. On entering Xcode (Version 4.0.2) you will see the following screen:

Xcode Welcome Screen
From here the easiest way to create a new project is to click on the “Create a new Xcode project” link. You will then be presented with the following screen, where you can choose from a variety of ready made templates to basic command line tool projects.

Select “Applications” under “iOS” in the left hand column and choose “View-based Application”.

Project Screen
You will now see the following screen. Enter “HelloWorld” in the “Product Name” box, and make sure “iPhone” is selected next to “Device Family”.

Project Name
Clicking on the “Next” button will take you to another screen where you will choose the destination of where you would like to save your project. After clicking on the “Create” button you will be taken to your new project. At first glance things will look scary, however for this project we will be concentrating on the left hand column which I have enlarged in the view below.

Inside Project
What you see above is all the files associated with your project. For this project we will only be interested in the following files:

  • HelloWorldViewController.h
  • HelloWorldViewController.m
  • HelloWorldViewController.xib

First we want to click on HelloWorldViewController.xib, which is the user interface (view) of your project. You should now see the following screen which is basically a representation of an iPhone app view with a grey background. If you do not see the inspector pane on the right which I have highlighted in green, either click on the icon (top right of your Xcode window) which I have highlighted in yellow or press cmd-alt-1. Here you will find the objects which you use to make up the interface.

Interface Builder First Screen
From the bottom right of the green highlighted panel, scroll through the “objects” until you find the “Text Field” object. You can also use the search box at the bottom to find an object.

Drag the “Text Field” on to the interface and place and resize it similar to the image below. As you move the object around the interface you will find that Xcode provides you with guides which the object will snap to, to help space and place objects correctly.

Add objects to interface
Add another “Text Field” object, as well as “Round Rect Button” and “Label” and position similar to the image below.

Objects on interface
Now, click on the top “Text Field” object, then in the inspector pane choose the “Attributes” inspector icon (highlighted in yellow). Here you can change the appearance of an object such as font, background colour, size etc… Find “Placeholder” which should be the second item down, and in the box enter “First name”. This should appear in the “Text Field” object and will give the user information as to what they are required to enter.

Do the same for the second “Text Field” object, entering “Last name” in the “Placeholder” box.

Adding placeholder names to text fields
Now select the “Button” object, and after selecting it, double click on it. This should allow you to enter text for the button, and type in something like “OK” (as below). Do the same with the “Label” object, however this time deleting the word “Label” leaving it blank.

Entering text into button
That is our interface done for now. We will now do the first bit of coding by declaring our objects and action in the header file (HelloWorldViewController.h)

In the header file we need to declare our outlets which are the our two “Text Field” objects, and the “Label” object, so between the curly braces { } enter the following:
IBOutlet UITextField *firstName;

What we are doing here is creating an “IBOutlet” object called “firstName” which is based on the “UITextField” class.

You will find that as you start typing Xcodes code sense (see image below) will give you some available options based on what you have typed. You can either continue typing yourself or find what you want from the list, and either double click on it or press the TAB key to complete the word.

HelloWorldController.h
Now declare the remaining outlet objects:

IBOutlet UITextField *lastName;
IBOutlet UILabel *msgLabel;

Now we will create the setters and getters (accessor methods) for these objects by adding the following between the } and @end:

@property (nonatomic, retain) IBOutlet UITextField *firstName;
@property (nonatomic, retain) IBOutlet UITextField *lastName;
@property (nonatomic, retain) IBOutlet UILabel *msgLabel;

When you start working through iPhone programming books, you will normally get a project similar to this. At this stage they do not go in to too much detail as to what statements like the above mean. What I will mention here though, is because we are using retain we will need to do something later with regards to memory management.

Finally we need to declare the action method for our button by adding the following after our three @property lines:

- (IBAction) sayHello;

What this says is we are declaring an instance method called “sayHello” which returns an IBAction. That is our header file finished for now and should look like:

Finished header file
Now it’s time to go back to our interface “HelloWorldViewController.xib” and hook our objects to the outlets and action we have just declared. First we will hook up the button action, so right click on the “File’s Owner” (the wire frame cube on the left), and you will get a pop up window like the image below. At the bottom you will see “Received Actions” with our “sayHello” action below that. Click in the circle to the right of “sayHello” then click/drag from here until you are over the button, then release.

Hooking up button action
You will now get another pop up window as seen in the image below. Choose “Touch Up Inside”.

Hooking up button action event
Right click on the “File’s Owner” again click and drag from the “firstName” outlet (top) to the “First name” “Text Field” object (see image below), then do the same with the “lastName” and “msgLabel” outlets.

Hooking up outlets
Your “File’s Owner” pop up window should now resemble the image below.

Finished file's owner window
We now need to go to “HelloWorldViewController.m” and implement our IBAction method. When you go to “HelloWorldViewController.m” you will see a lot of boilerplate code which Xcode has supplied you with. We won’t worry about any of that for this basic project.

After @implementation HelloWorldViewController we need to synthesize our outlets so add the following three lines:

@synthesize firstName;
@synthesize lastName;
@synthesize msgLabel;

Next we need to code up the IBAction so add the following:

- (IBAction) sayHello
{
NSString *msg = [[NSString alloc] initWithFormat:@”Hello %@ %@”, firstName.text, lastName.text];
[msgLabel setText:msg];
}

We start off by opening our IBAction method. We then create a new NSString object called “msg” and populate it with “Hello” followed by “%@ %@” which is two variable placeholders. The variables to use are now declared by “firstName.text, lastName.text” which is basically saying the text that comes from the two text field objects. We then populate the label with our new “msg” object.

The top of your “HelloWorldViewController.m” should now look like:

HelloWorldViewController.m code
We are now at a point where we can run our project and see what happens when we enter our name and press the “OK” button. There are a few ways to run your project, for instance – pressing the “Run” button at the top left of your Xcode window, or pressing cmd-r. Either of these will build your project checking for errors and compile it to run in the simulator (make sure you have one of the iPhone simlulators selected from the device drop down menu next to the “Stop” button at the top left of your Xcode window.

You will now see something similar to the image on the left below. By clicking one of the text boxes, the keyboard will appear from the bottom just as if you were say writing an email on your actual device.

Simulator view
Enter your first and last names in the boxes and press the OK button. You should get something similar to the image on the right above. There are couple of things not quite right here. Firstly the keyboard does not disappear when you press the “OK” button, and secondly what you entered in the boxes is still there. If you want to rectify these two points then read on.

Go back to “HelloWorldViewController.m” and add the following before the NSString line:

[firstName resignFirstResponder];
[lastName resignFirstResponder];

What happens here is whichever test box was tapped on first becomes the “first responder” which opens the keyboard. So what we do now is say [firstName resignFirstResponder] which means that if this text box was tapped on first then “resign” its status as “first responder” which makes the keyboard disappear. We then repeat the statement for any other text boxes in the UI.

Now add the following below the NSString lines to empty the text boxes:

[firstName setText:@""];
[lastName setText:@""];

Finally, earlier I mentioned with regards to the @property statements, that because we were using retain we would have to do something with regards to memory management. In the HellowWorldViewController.m file you will probably see a method of -(void)dealloc which was added automatically by Xcode. This method is to do with memory management, which I won’t go into in detail at this stage, however because we used retain for the three UI objects we need to release them from memory. So within this method we need to add the following three lines:

[firstName release];
[lastName release];
[msgLabel release];

The top of your “HelloWorldViewController.m” should now look like this:

Completed HelloWorldViewController.m file

Now run the project again, enter your name, press OK and you will see the text boxes back to normal, and the keyboard disappear as below.

Final simulator view
And there you have it your first project. Here I have added slightly more functionality than a Hello World project from most books to show you how to do some basic interaction between user input and user action.

Programming in Objective-C 2.0 (3rd edition) by Stephen Kochan

Whilst waiting for what seems like forever for the third edition of Programming in Objective-C 2.0 by Stephen Kochan to arrive, I decided to cancel my order with Amazon.co.uk and purchase it from Amazon.com as it is already available in the US. Yes, I have had to pay extra for P&P, however as Amazon.co.uk do not have a proper available date I could not wait any longer, so hopefully I will receive my copy from across the pond by the start of next week, and get down to the nitty gritty of learning Objective-C.

Up until now I have been watching the Stanford lectures as previously mentioned, however the students attending these lectures are expected to have completed a module on Java, so will have a very good grounding of an OOP language. Don’t get me wrong, the three lectures I have watched so far have been informative and am sure will come together even more once I start working my way through Stephen’s book.

I have also been working through a couple of books on iOS programming, which although do not teach you Objective-C from the ground up, they lead you through building various basic apps, giving you a grounding in Xcode. The main problem I had was that most of the books out there are based on Xcode 3.0, and as I am using Xcode 4.0 (not used 4.2 yet as it scares me), I got a little lost at times. I managed to find one book which is based on 4.0 (iOS SDK Programming A Beginners Guide). One thing I have found working through these books though is that when my projects do not run I have had trouble a couple of times figuring out what is actually wrong. This may be due to an error in the code from the book, and therefore the fact that my knowledge on Objective-C is limited at the moment, I am not always able to fix it. But hey, it’s all good fun, and when it does work and I am able to run the app (all be it basic apps) on my iPhone it brings that smile back to my face.

Based on what I have learned so far though the books mentioned above, I will be uploading a guide to producing your first app shortly. Yes, it will be the usual “Hello World” app which most programming books have you producing first, however we all need to start somewhere.

Apple Developer Programs

When I initially installed Xcode I also registered myself as an Apple Developer, which is free to do, and gives you access to certain areas within the Apple Developer website.

There is however another option which is to become a paid up iOS Developer, which costs $99 a year. I guess the main reasons one would become a paid up iOS Developer is that you can test your apps on your own device, instead of using the simulator application which comes with Xcode (and has its limitations), and of course you will be able to submit your app to the app store.

Initially I decided not to become a paid up member until I was in the position of having developed my first “proper app”, however through the recommendation of a figure already in the industry who I have established contact with recently, I have now become a paid up iOS Developer.

So why change my mind? Well I was informed of the extra benefits such as video tutorials on the latest SDK’s etc, as well as being able to download the latest betas of the SDK and Xcode. So the first thing I did was download the latest betas of Xcode (4.2) and SDK 5.

Of course after installing the download I decided to launch Xcode and see if there were any initial notable changes. Unfortunately due to NDA, at this time I cannot discuss any differences in Xcode 4.2/SD 5 to the previous version.