Objective-C Functions

computer-coder-150x150A function in programming is a discreet area of code that is independent from the rest of the program. Functions are also called subroutines and as that name implies functions are a bit like small programs. Generally, functions may accept variables as inputs and a function may produce a value as an output.

Take a look at figure 1 to see what all the pieces of a function look like before we discuss each piece separately.

Figure 1: Anatomy of a Function

Return Type

Something that a function can do is produce a result based on information that you give to the function. A result can be a number like an integer or float. Functions can also return other primitive types like Boolean values like YES and NO as well as characters like A or B.

Take a look at figure 1 to see where the return type belongs in the function declaration. Our function returns an integer as a result so we use the int keyword to indicate this.

int productOfTwoNumbers (int number1, int number2){
     int result;
     result = number1 * number2;

     return result;
}

This works in the same way as it does for declaring variables so you can see return types specified with int, BOOL, float, double and char.

Functions can even have a return type of nothing at all! What? Why? Sometimes we want to separate part of our program but we do not need a result. In those situations we will would like to use a function but we do not need to get a result back.

To code a function that does not return a value you may use the void keyword. Another difference with functions that use void to specify that they are returning nothing is that they may omit the return value statement.

Function Name

The next part of the function declaration is the function name. The function name goes right after the return type which you can see clearly in figure 1.

int productOfTwoNumbers (int number1, int number2){
     int result;
     result = number1 * number2;

     return result;
}

We use functions to attack a big problem by first breaking the big problem up into manageable chunks. Now we can treat each chunk on its own. When we are satisfied that each chunk works the way that we expect we can then use those functions together to solve our bigger problem. Let’s see how to use functions.

Parameters

Functions can accept inputs as well as return output. Inputs are information that will be used in the function. You can specify the inputs for a function in the parameter list. The parameter list is a list of variables enclosed in parenthesis that are placed right after the function name. In the figure 1 you can see that we specify two integers as parameters.

int productOfTwoNumbers (int number1, int number2){
     int result;
     result = number1 * number2;

     return result;
}

You declare parameters in the same way as you do variables. They are located right after the function name in parenthesis and each variable is separated by a comma.

Function’s Code Region (Scope)

We talked about the notion of scope already. Functions get their own region of code with has it’s own scope. This region is defined starting with the first curly brace after the parameter list and the region ends with the match curly brace after the function’s last line of code.

Any variable that you code within these curly braces will only be in scope from within the function’s curly braces. This gives us a great way of keeping the code that only belongs in the function separate from the rest of the program. In function displayed in figure 1 all the code that falls between the curly braces is in scope for the function.

int productOfTwoNumbers (int number1, int number2){
     int result;
     result = number1 * number2;
     return result;
}

Return Value

For functions that will return a result we need to use the return keyword to specify what variable value will be returned to the code that is using the function. Return values serve as the output of the function. Return values must match the type declaration of the function. So, if you declare a function with the return type as an integer they you must be sure to return an integer in your return statement.

In figure 1 we use the integer variable we called result to temporarily store the result of our calculation. At the end of the function’s region of code we use the return statement to return the result value back to the program.

int productOfTwoNumbers (int number1, int number2){
     int result;
     result = number1 * number2;

     return result;
}

We use functions to attack a big problem by first breaking the big problem up into manageable chunks. Now we can treat each chunk on its own. When we are satisfied that each chunk works the way that we expect we can then use those functions together to solve our bigger problem. Let’s see how to use functions.

Calling Functions

So that is how you declare a function. To use a function you use do must call the function from the main program. So, if we were to assume that the function from figure 1 was declared in a place that allowed our main program to get access to it we could use productOfTwoNumbers.

The first thing we would need from the main program is an integer to hold the output value that the function is going to return to us.

int resultOfFunction;

Now that we have something to hold the value we can call the function and assign the result to our resultOfFunction integer.

int resultOfFunction;
resultOfFunction = productOfTwoNumbers(5, 4);

Calling the function works by including the function name with parameter values in parenthesis after the function name. The parameter values that you provide here in the function will be assigned to the parameters declared in the function. These may then be used by code in the function. In the code above resultOfFunction will now contain the value returned from the function which in this case is 20.

Where To Declare Functions

Now that you have an idea of what a function looks like it’s time to go through the process of adding a function to your app. For the first example we can simply add the resultOfFunction function to an XCode project.

Add Header And Code Files

Functions are used to split big problems into smaller problems that are easier to solve, but they are also a way to re-use our coding work. The idea is that if you create a function that solves a math problem (like our example in figure 1) then you may want to use that function in many parts of your program. You may even want to use this function in other programs and apps. If you code a really great function then you may even want to share this with other programmers.

To make sure that we can do this we must code our functions in their own code files. Our files can have more than one function in them, but you should take care to only include related functions in the same file.

Functions must be coded in two files. The first file is called the header file (this is also called the interface file). The header file has a file extension of .h. This second file is an implementation file and ends in .m. Let’s add these two files to our XCode project before we talk about them further.

To add a new file to your XCode project, select XCode’s main menu and then select File > New > New File…. You will see a dialog box that pops up and looks like figure 2. Choose iOS > Cocoa-Touch > Objective-C Class.

Figure 2: Add New File Dialog

Now click Next and name the file Functions. You should now see two new files appear in the XCode project’s group folder called Functions.h and Functions.m.

Let’s talk about what goes into each of these files next.

Header Files

The header file is used to specify what is called a forward declaration. A forward declaration is a declaration of a variable, function or type when the complete definition has not yet been given. What you are doing when you use a forward declaration is telling the program that some will be defined in the future that matches the specifications that we outline in the header file.

Our header file will contain a forward declaration for the function we are looking at in figure 1. We can code this by simply typing out the very first line of the function from figure 1 and replacing the curly brace that would start the function’s region of code with a semi-colon.

Click on the Functions.h file that was created for you in the previous step. You will see a file that has some comments written in.

Note: comments are the green text that start with /* and end with */

Your file will look something like this except you will have your own personal information include here in place of mine.

//
//  Functions.h
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Functions : NSObject

@end

The first thing we need to do is to erase all the code that is in this file except for the #import statement since we do not need the boilerplate code that XCode provides for us right now. Your revised Functions.h file should look at this:

//
//  Functions.h
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import <Foundation/Foundation.h>

Now that we go that out of the way we can add the forward declaration for our function just type into this file after the comments.

//
//  Functions.h
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import <Foundation/Foundation.h>

int productOfTwoNumbers (int number1, int number2);

Now it is time to move on to writing the code to make this function work in the implementation file.

Implementation Files

Implementation files are where we put the code that was declared in our forward declaration. This is where all the work of the function gets done. Click on the functions.m to see the contents of the implementation file that XCode created for you.

//
//  Functions.m
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import "Functions.h"

@implementation Functions

@end

This looks like the header file except that we have this #import statement added at the top of the file. This #import imports the forward declaration into this file for us. Like the header file we have some extra code in the implementation file that we need to get ride of for our example.

Get ride of the extra code XCode put in here for by deleting the lines starting with @implementation and @end. When you are finished your file should look like this:

//
//  Functions.m
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import "Functions.h"

Now what we need to do in this implementation file is to add the function.

//
//  Functions.m
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import "Functions.h"

int productOfTwoNumbers (int number1, int number2){ int result; result = number1 * number2; return result; }

That is it – we now can use this function from anywhere in our program by taking a few key steps. Let’s do that now.

Calling Functions

Let’s use our function in our app. Select the file in your XCode project named AppDelegate.m. Your app delegate file will look something like this:

//
//  AppDelegate.m
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate
@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

@end

The first step that we need to take to call our function is to import the header file into our app delegate. You can do this at the very top of the file after the automatically generated comments.

//
//  AppDelegate.m
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import “Functions.h”
#import "AppDelegate.h"

@implementation AppDelegate
@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

@end

Importing the header file gives us access to that function so now we can use the function in the same way we learned before. Declare an integer variable named result and use the function to assign a value to result. You should put this code in the didFinishLaunchingWithOptions method.

//
//  AppDelegate.m
//  functions
//
//  Created by Matthew Campbell on 10/25/11.
//  Copyright (c) 2011 Mobile App Mastery. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate
@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    int result = productOfTwoNumbers(3, 6);

    return YES;
}

@end

Now the value of result will be 18 because we called the function productOfTwoNumbers with the parameters 3 and 6.

Hands-On Time

In the last chapter, you wrote code help a user generate secret codes. Essentially, what you did was create a switch statement that used the value of a variable to transform a letter into a character and vice versa. For this exercise, create two functions based on that code.

The first function should be called encryptThisLetter. encryptThisLetter will have one parameter of type char and it will have a return type of int.

The second function will be used to decode and the function should be called decryptThisNumber. This function will have a parameter of type int and it will return a type of char.

Leave a Reply