Learning Unit Testing in XCode 5

I have been delaying in learning Unit Testing ever since the released of XCode 5 on September 2013. It is partly due to my busy schedule in rushing 2 complex projects back to back. Now the Second project – Watch Over Me 3.0 is under the beta testing stage, so, I have some time to pick up some skills that I have been wanting to learn.

What is Unit Testing?

Unit Testing is part of Agile Software Development Methodology to make the entire software development process more efficient, the development project to be easier to maintain, less crashes on deployed software and higher quality of code.

Automatic Unit testing, on the other hand, is a proactive way to test a small unit of codes (functions, classes) from time to time to make sure that they are always ready for production. You can host a test server (eg: OS X Server) together with Git repository server. On the test server, some bots will test the latest commits of the codes frequently.

Unit Testing in XCode 5

Apple has done a great job by providing us (The iOS developer) with good framework that can help us to implement unit testing easier on XCode 5. I have learned this unit testing through WWDC 2013 video – Testing in Xcode 5 by Mike Swingler.

From what I learned from the video, we all should start the Unit Testing from Model and Controller. XCode 5 has been designed to make the Testing between the Model and Controller really easy. The new framework for the testing is XCTest.framework. This framework is derived from OCUnit. The iOS developers have been using OCUnit framework prior to XCode5. So, the previous testing codes are compatible with XCTest framework. If you were using OCUnit, you only have to refactor your old code to make it running well with the new framework.

While I was trying to implement the Unit Testing on my old personal Calculator XCode project, I found this simple tutorial (CS305 Software Engineering – Unit Testing in iOS). It shows me some steps and codes using a different calculator project. I learned something new from it.

Be warned, this project is old and it is definitely not optimized for iOS 7.

Example of Unit Testing in Calculator App

I just implemented what I have learned from the video on an old Calculator app project that I have developed for fun some time ago. This is not a usual calculator that most people are familiar. This is a RPN (Reverse Polish notation) calculator.

For example, if you would like to calculate an operation such as 21 + 63, the steps that you have to follow are:-
1. Press 2 and 1
2. Press Enter
3. Press 6 and 3
4. Press Enter
5. Press +
6. Press Enter

You will then get the result showed like the screen below:-
Unit Testing on XCode 5 With Example Project

Unit Testing can be further divided into 2 parts:
1. Logic Unit Testing
– Test only the logic with fixed values and without human interaction
2. Application Unit Testing
– Simulate the user inputs by using user interface such as button and make sure that the app behaves the way it should.

To keep make thing simple, I will only implement Logic Unit Testing for now. I will add more examples when I learn deeper into this Unit Testing.

The Model of my calculator project is CalculatorBrain. It has 3 functions:-
1. pushOperand
2. performOperation
3. popOperand

So, I will perform the unit testing on these functions.

There are only 4 major operations:-
1. Addition (+)
2. Subtraction (-)
3. Production (*)
4. Division (/)

I will implement Logic Unit Testing for all these 4 operations but I will only show an example in this article.

When a user is trying to add 21 with 63, he/she should get the result as 84. Or else, this operation will fail. Here are the steps:-

1. I import CalculatorBrain.h into CalculatorTests.m.
2. I create an instance of CalculatorBrain and instantiate it in setUp method.
3. I create a method calls testAddition.
4. I push 2 numbers (21, 63) using pushOperand.
5. Then, I use performOperation to calculate the result.
6. Lastly, I compare the result with 84 using XCTAssertTrue.

If the logic testing is good, it will show you the following result on the command line:-

If the logic testing is wrong, it will show you something like:

You then will know that you have made a mistake somewhere in the code, you will have to find a way to fix it.

The screen below shows you the complete unit testing for all the 4 operations.
iOS Unit Testing by Example XCode 5

Final Thought

Unit Testing is really an interesting way that helps us to be more proactive in programming. This is especially true when we are able to implement the Bots that help us in testing the project automatically.

You can find the full source code for this simple Unit Testing that I uploaded to Github here: iOS Unit Testing By Using Calculator Project on XCode 5.


How to Use Container View Controller

Container View Controller is one of the interesting View Controllers that I used recently in XCode. Apple has provided many standard view controllers for iOS Developer in XCode such as Table View Controller, Tab Bar Controller, Navigation View Controller for most common standard projects for iOS developers. But for a certain projects with unique design, we have to use container view controller.

I have been using container view controller for a while and I love it. Here is a simple guide on how to use it. I will create a simple mobile app with 3 different view controllers:-

Simple Container View Controller Programming Example

1. MainVC
2. ProfileVC
3. Menu VC

– Contain a navigation with 2 buttons.
– When the Profile button is clicked, the MainVC will slide to left and the ProfileVC will appear.
– When the Menu button is clicked, the Main VC will slide to right and the MenuVC will appear.

Profile View controller
Main View controller style=
Menu View controller

Container View Controller Project Setup

Update: I have been busy for the last few months, just updated this post on February 2014.

Step 1: Create a new project and delete the existing .h and .m file that was created by the XCode

Step 2: Create the subclasses below:-
MainVC, MenuVC, ContainerVC and ProfileVC subclass of UIViewController
ShareSetting subclass of NSObject

Step 3: Link the existing view controller objects on storyboard with ContainerVC.

Step 4: Drag and drop the Container View in storyboard into the ContainerVC View Controller object. Rename this Container View as “MenuVC”. The position and side for this container view should be X: -260 Y: 20 Width: 320 Height: 548. Attach the MenuVC subsclass to the view controller comes with the Container View.

Step 5: Drag and drop another Container View into the same view controller and name it as “ProfileVC”. X: 260 Y: 20 Width: 320 Height: 548. Remember to attach ProfileVC subclass to the created view controller.

Step 6: Drag and drop the last Container View and name it as “MainVC”. X: 0 Y: 20 Width: 320 Height: 548. Attach the subclass to the view controller.

Step 7: Change background for each view controller object (MainVC, MenuVC and ProfileVC) to different colors.

Step 8: Add a title to MenuVC and ProfileVC

Step 9: Add a simple navigation bar and 2 buttons to MainVC.

If you are doing correctly, you should see a screen shot similar to below:
Simple Container View Controller Programming Setup

Container View Controller Coding

1. ShareSetting
– This class is basically used to share actions/behavior for the same buttons across a few different view controllers. Although in this simple project, we only have 1 view controller that uses the buttons. In more complex projects, we usually need this ShareSetting. Add the following codes to the class.

In ShareSettings.h

In ShareSettings.m

2. ContainerVC
– This is the main class that control the animation behavior for 3 different view controllers (MainVC, MenuVC and ProfileVC)

In ContainerVC.m

3. MainVC
– This is the Main View Controller which contains the navigation bar, the Menu Button and Profile Button.
– The 2 buttons that were created on the storyboard should be “Control + Drag” into the subclass. So that there will be 2 functions created in the subclass and every time the button is tapped, we will receive the action in the functions.

Last Step: You are done! For your information, the MenuVC and ProfileVC subclasses are created but there is no function for this simple example. You may add tableview to MenuVC and create a real profile for ProfileVC by adding some text field, photo and etc.

For more information, you can check Out: View Controller Programming Guide for iOS

Simple Calculator iOS Application

The First assignment that I did when following the Stanford iPhone / iPad Development course was the Simple Calculator iOS Application. In this post, I am going to share every step in making this mobile application.

Create a New Project

First of all, launch the Xcode and create a new project using “Single View Application“.

Under Product Name, you may put “Calculator”. Put your name or your company’s name under organization name.

As for Company Identifier, it is usually the reverse characters of a web domain that you own. For example, if you own “abc.com” then you put it as “com.abc”. If you do not own any web domain, you can just put any domain such as “com.example”. It is not important for now if you just want to run the application on simulator. But, when you want to run the application on your mobile device, you should get your own domain. You will also need to do some provisioning settings on the Apple Developer Portal, attach the provisioning certificates on your Xcode before you can run it on your device and also submit the application to Apple. I will do tutorial on that in a later post)

Under the Class prefix, you can put it as “Calculator”. Choose “Universal” under Devices as we will build both iPhone and iPad app. Tick “Use Storyboards” and “Use Automatic Reference Counting (ARC)“. We want to use Storyboard as it is an important technology that simplifies the implementation of MVC in iOS. Before iOS 5, the developers have to take care of every object creation and destruction to manage the memory. But, Apple has released a new technology calls ARC which simplifies the memory management in Xcode.

After you click “Next”, you will be asking to choose a place that you want to create this project. I normally put it under a “Developer” folder just to keep everything organized. After you click “Create”, you will see a screen like the below screen shot:-

Your project will have 2 AppDelegate files (.h, .m), 2 storyboards (for iPhone and iPad) and 2 ViewController files (.h, .m). .H is a header file which can be accessed by public while .M is a implementation file which can only be accessed by the class itself (private).

The storyboards will contain all the views for our controllers. So, the initial project creation has given us both the view and also controller. We will create our own model later.

Creating Our Views

We will leave iPad storyboard for now until the end of the tutorial. So, let’s start with the iPhone storyboard. From the storyboard, you will see an iPhone size view controller object on the screen. When you click the “view” inside the view controller object, you may see the height for the view is 548. It is actually the iPhone 5 size. We can click a small screen toggle button on the bottom of the page to toggle it to normal iPhone height which is 460. We will optimize for iPhone 5 later. But for now, we just want to keep it simple and start with normal iPhone size.

How to Implement MVC in iOS Using Xcode

If you have just started to learn iOS Application programming, Some of the questions that come to your mind could be: “What is the best way to program in Xcode IDE?”, “Should I use purely coding? Code + Interface Builder? or Code + Storyboard?”

From my own experience working with some iOS apps developers, I learned that some of them are still using pure coding with some Interface Builder. It means that they haven’t adopt the latest technologies in Xcode provided by Apple. I can not totally blame them, it is because they are developing iOS projects that have been there for a few years and to change everything to the latest technologies is not an easy task to do.

For a fresh new iOS project, it is the best to adopt the latest technologies provided by Apple. It means that we have to use both Code + Storyboard to make the iOS applications.

MVC in Objective-C and Xcode

How do we implement MVC Using Xcode? Here is the quick summary:-

Model: Model is always in coding. It can be in its own class (with .h and .m). But sometimes, we can code a simple Model inside a view controller.
Controller: It always has its own class (with .h and .m). However, Apple has done a great job by making us to be able to see the view Controller in Storyboard. So, we can create a dummy (without function) view controller object on Storyboard. Then, we link this view controller UI Object with our own custom class file (.h and .m). We can code the functions inside the .h and .m files.
View: You can display a view using coding but it is not recommended since the release of storyboard. So, we always create view objects on Storyboard. We just drag and drop the GUI Objects into the View Controller. If we need to have special customization of object, we can subclass that object and manipulate it using code. But most of the time, we do not have to do that as the existing customization properties on the Xcode is already good enough. When a certain objects want to communication with View controller using (Target-Action), we just need to CONTROL drag that element into the .m file. As for Delegate and DataSource, we will implement it on the View Controller files.

Here is the detail explanation on Model, View and Controller with some visual explanations.

If you take a quick look at the Xcode, you will find out that there are many ready to use GUI (Graphic User Interface) Objects such as Button, Text Field, View and even View Controller. You can easily drag and drop the GUI elements into the storyboard. So, Views are mostly available on the storyboard.
View Controller Objects

There are a lot of customization properties inside the view object as well. For Example, you can change the shape of a button, change the title, color, font, image, background image, shadow and more.
UIButton Properties

If you remember the previous post on: Programming in iOS with Objective-C Using MVC, A view can only communicate with view controller using 3 different methods and Target-Action is one of them.

The below are the steps for creating Target-Action for Button to inform the View Controller when the user has clicked the button.

Step 1: Control + Drag the button into the .m implementation file.
Target-Action 1
Step 2: Enter a function Name and also type of sender.
Target-Action 2
Step 3: A function is created and you can start to code the body of the function.
Target-Action 3

For View controller, the below shows the .h and .m files.
dot H and dot M files for view controller

We can always link the custom class (.h and .m) with the view controller object on the storyboard. We can implement various functions using coding.
Custom class in Xcode

Programming in iOS with Objective-C Using MVC

One of the early concepts that I learn from CS193P iPhone Development Course by Stanford University is MVC (Model, View, Controller). MVC is not a programming language. MVC is not a platform. It is a Software Architecture Design Pattern.

When you want to build a house, you will need to hire a construction architect to plan and design the blueprint of the house. The proper planning and designing is very important to make sure that the house will not collapse, to make sure that the resources are used properly and to make sure that the cost is within the budget.

It is the same with any software application development. If you want to build a great software that will not crash frequently, small in size, user friendly and good response time, lesser lines of codes, easy to debug, easy for other programmers to understand, then you will have to develop the software by following a good programming architecture pattern. So, MVC is the Blueprint of a software development project.

Objective-C is built upon Model, View, Controller (MVC) Design pattern. Apple expects all the iOS programmers to follow this programming architecture pattern. If you want to build a simple mobile application, you can easily get away with it without following the exact MVC patterns. But, when you are building a complex app with many features that needs frequent updates, you will run into a lot of trouble. At the end, you will be wasting a lot of time when trying to convert Non-MVC code to MVC code.

So, before starting a new mobile application development project in iOS, you will have to plan properly using MVC.

What is MVC (Model View Controller)?

Like Professor Professor Paul Hegarty mentioned in the lecture. We can consider MVC as 3 different camps.

Model – What your application is about? (Data, Logics, Rules)
Controller – How you present your application (model) to the end users?
View – The interface which the end users see

What is MVC (Model View Controller)?

A Short Explanation on MVC

Controller always sits in between the Model and View. View does not own the data that it displays. View and Model can not have direct interaction with each other. View gets the data from Controller when the Controller implements itself the datasource of the View. The controller normally will get the data from Model before passing it to View. Only Controller have the freedom to initiate the direct communications to View or to Model. View and Model can communicate with Controller using some indirect methods explain below.

View can inform Controller for a certain events in 3 ways:-
a. Target-Action (eG: buttons)
b. Delegate (Will, Did, Should)
c. Data Source (data at, count)

Model can communicate with Controller only through:-
a. Notifications
b. KVO (Key-Value Observing)

MVC Real Application Examples

Example 1: Creating a Simple Calculator App.
a. The logics of calculating the equations is the Model.
b. The number buttons, arithmetic buttons, the result displaying text are the Views.
c. The View Controller sits in the middle of Model and View.

The Simple Flow: The View Controller gets the inputs (via buttons) from the users and send the inputs to the model. The Model will calculate and send the result back to Controller. Lastly, the controller will present the result on screen via a Display view.

Example 2: Building a University Final Exam Result Application.
a. The Model is the database of the results
b. The View is the Table View/List View that shows the name of students, student ID, Grade, CGPA, total marks, Credit hours.
c. The Controller gets the data from database and shows it on the Views.

For this Exam Result Application, we do not need input from the users, we only need to present the data to the users. So, the model is slightly different comparing with the Calculator App. For View and Controller, they are always the same. View handles the interfaces for the end users and Controller handles the interaction between Model and View.

You might ask, why can’t we just show the data directly from Model to View? Why do we have to go through the hassle to create Controller? Answer: It is to make the programming in a simple and manageable way. When we want to troubleshoot a simple bug, we will know exactly where the bug is (either Model, View or Controller). From there, we can easily find the appropriate classes and find the bug from there.

Here is the example MVC Design vs Non-MVC Design:-
As you can see from the following graph,

When MVCs are Working Together:-
Model View Controller Working Together
The above diagram show how the MVCs working together. You can see that the MVCs have simple and manageable flows. Each of the pointers are obeying the MVC rules.

When MVCs are Not Working Together/ Non-MVC:-
Non-Model View Controller
MVCs are not working properly on the above diagram. I just simply call it as Non-MVC. From the diagram, the flows of the pointers are everywhere. It is not a good design. When there is a bug, you do not know where to start the debugging.

For more details on Model, View and Controller, you can read from wikipedia: MVC (Model View Controller).

Understand the 4 Layers of iOS

4 Layers of iOS - Core OS, Core Services, Media, Cocoa TouchAs per the course in Standford, Professor Paul divides the iOS into 4 different layers. Core OS layer is the closest to the hardware while Cocoa Touch Layer is the closet to the user Interface. In most simple iOS projects, we probably will spend 90% of the time on Cocoa Touch layer. But, if you are building some specific location based mobile apps, then you probably will spend more time on the Core service Layer.

The following are parts of the frameworks/features for each of the layers:-

Core OS
– Power Management
– Keychain Access
– File System
– OSX Kernel
– Sockets
– Security

Core Services
– Collections
– Address Book
– File Access
– SQLite
– Core Location
– Threading
– URl Utilities
– Networking

– Core Audio
– Core Animation
– Audio Recording
– Quartz (2D)
– OpenGL ES

Cocoa Touch
– Multi-Touch (Gesture)
– View Hierarchy
– Localization
– Alerts
– Web View
– Map view
– Image Picker
– Camera
– Buttons

Most of above information and source of images are taken from Stanford University iPhone Application Development course.