Tag Archives: Object Oriented Programming

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

Objective-C: Inheritance

If you read my last post on Objective-C: Classes and Objects, you would have seen mention of the Car class inheriting from the NSObject class. You may also have encountered a description of OOP inheritance in a previous post on Object Oriented Programming, and be wondering how this works in relation to Objective-C.

In a class interface file you will see something like:
@interface MyClassA : NSObject
This is basically Objective-C inheritance at work. Within the methods you have set up for your MyClassA class, which is also known as the subclass or child class, you can use instance variables and methods of the NSObject class, which is the superclass or parent class of MyClassA. NSObject is the root class in Objective-C, meaning it is at the top of the hierarchy, so has no classes above it.

Now you can set up a new class called:
@interface MyClassB : MyClassA
which will inherit the instance variables and methods from both MyClassA and NSObject, as MyClassA already inherits from NSObject. Each instance of a class receives its own instance variables, even ones inherited from parent classes.

I hope this helps to clarify inheritance and how it is implemented in Objective-C.

Objective-C: Classes and Objects

In his book Programming in Objective-C 2.0, Stephen Kochan uses a very good way of describing classes and objects: An object is a “thing”. Think about object-oriented programming as a thing and something you want to do with that thing. He then goes on to describe the concept of creating a class using a “car”.

So, we start with the class name which is Car (class names in Objective-C should begin with a capital letter).

A class can be made up of attributes (instance variables), and methods (things the class can do). So for a car, the attributes could be:

  • Exterior colour
  • Interior colour
  • Roof type
  • Engine Size
  • …and many other attributes

Some of the instance methods for a car could be:

  • Drive
  • Fill up
  • Service
  • Wash
  • …and many other methods

A class method for a car could be:

  • How many types of car a manufacture makes

So what is the difference between an instance and class method? An instance method applies to each individual car object (class instance), whereas a class method performs some function on the class itself, such as creating a new instance of a class.

To set up the Car class you would start with the interface section, where you declare the attributes and methods:
Car interface
First we have the @interface declaration, followed by the class name Car and NSObject which is the parent class of this class, meaning that the Car class inherits attributes and methods of the NSObject class.

Next, inside the curly braces {} we declare the instance variables. Here I have simply chosen a sample of possible attributes for this class.

Then, after the attribute declarations and just before the @end statement we declare the instance methods.

We now implement the methods for the class in the implementation section:
Car implementation
I haven’t gone into detail here, however you can see that inside the @implementation and @end we have our four instance methods ready for their respective implementation code to be inserted.

Once you have the interface and implementation of the class set up you are ready to create car objects (class instances), which is done as follows:
Car object
Here I have inserted the code inside main.h as I created a basic command line tool project, however it will be inside a specific .m file inside an iOS project.

First we create and initialise a new car object by saying we are creating a new Car called myCar and sending a message – alloc (which with we have inherited from the NSObject class) to the Car class, then initialising it.

We can now send messages to our myCar object to drive, service etc…, and finally when finished with the object we release it from memory (which I will discuss at a later date).

We can also create new car objects that use the same methods as myCar, although are individual to each car object (as mentioned above). This is one of the key concepts of object oriented programming.

I have not gone into great detail here as my intention was to give an overview of classes and objects in relation to Objective-C.

OOP Encapsulation

In my previous post on the topic of Object Oriented Programming, I briefly touched on encapsulation as “A class is created by putting related things together (encapsulation) from which an object can be created. The programmer will encapsulate attributes and methods that are related to a particular object.”

This was my understanding from reading a previous text, however on reading Stephen Kochan’s Programming in Objective-C, he has made the subject of encapsulation easier to understand in relation the Objective-C language.

“What if you wanted to access your instance variables from someplace else – for example, from inside your main routine? You can’t do that directly because they are hidden. The fact that they are hidden from you is a key concept called data encapsulation…”.

He goes on to say “You can access your instance variables in a clean way by writing special methods to set and retrieve their values”, and describes the theory of setters and getters, and how to set them up manually. As I have already worked through some chapters of an iOS programming book, I have already come across setters and getters, however did not realise their relevance to the subject of encapsulation.

With regards to setting the setters and getters manually, Steve does this so that you learn the theory, as later in the book he will go on to describe the @property and @synthesize statements for setting up the setters and getters easier.

Object Oriented Programming (OOP)

Objective-C is an object oriented programming language which is built upon the procedural language C, using OOP messaging based on Smalltalk. Although I had a basic idea on OOP through my University course, I recently purchased OOP Demystified (A self-teaching guide) to give me a deeper understanding of the concepts, which will help when I start looking at Objective-C in depth.

In this post I will share with you my understanding of the basic concepts of OOP. OOP is a rather deep subject and you may want to look into this further yourself as the book mentioned above also covers areas such as identifying and describing objects, modeling, and interfaces.

There are some terms related to OOP which you will probably hear of or read about as you delve further into Objective-C or other OOP languages yourself. Some of these are:

  • Encapsulation
  • Inheritance
  • Polymorphism

The main concept behind OOP is the defining of classes from which you can create objects. A class is the blueprint of an object, and each time you create an object, the class definition determines its structure. A class consists primarily of attributes (characteristics) that can store data, and methods (actions) that can perform operations. An object can also be called a class instance, and you will hear the terms class and instance variables used in Objective-C.

A class is created by putting related things together (encapsulation) from which an object can be created. The programmer will encapsulate attributes and methods that are related to a particular object.

Say for instance you were writing a program for a university. For this you would need to create objects for the students of the university. You would think of the various attributes that the student would have, and assign actions which would relate to a student. This is demonstrated in the diagram below:

Class disgram

Polymorphism

Polymorphism is where you can have many class which have methods of the same name. You would do this when you have two or more classes whose methods perform similar tasks, but are completely different in the tasks they perform. You can give the methods in the two classes the same name, thereby alleviating the need to remember too many different method names.

Inheritance

Inheritance is where objects can use attributes and methods from other objects. This will cut down on the amount of code you will need to write as you simply send a message to another object to use its methods. Inheritance works using a parent/child hierarchy system, whereby the child class can access attributes and method of the parent class, however this cannot be done in the other direction.

Inheritance can be shown by going back to the university program. As mentioned earlier you would have a class for student. You could have another class for graduate students, which could inherit attributes and methods from the student class. The diagram below shows the classes for Student and GradStudent:

Inheritance Diagram
As you can see in the diagram above we are using polymorphism, in that both classes have methods called Write and Display. Also, there is no need to add attributes such as first name, last name etc. in the GradStudent class as these are inherited from the Student class.

There are three ways in which inheritance can be implemented: simple (shown above, multiple, and level inheritance). Multiple inheritance is where the inheritance involves multiple parents to a child:

Multiple inheritance
Level inheritance is where a child inherits from a parent, and in turn becomes a parent itself. With level inheritance the maximum amount of levels that would be used is three, as things start to get complicated after that:

Level inheritance
So how do we decide between multiple and level inheritance when the child inherits directly or indirectly from more than one parent? Here we use the “is/are a” method:

Level Inheritance

Hopefully this gives you a basic understanding of object oriented programming. I do however suggest you do some further reading in relation to areas such as identifying and describing objects.