Functions and Methods in Objective-C

Functions and Methods in Objective-C,A function is a named block of code that can be called upon to perform a specific task. It can be provided data on which to perform the task and is capable of returning a result to the code that called it.

The function can be programmed to accept the values on which the arithmetic is to be performed and to return the result of the calculation. At any point in the program code where the calculation is required, the function is simply called and the result returned.

Declare an Objective-C Function

An Objective-C function is declared using the following syntax:
<return type> <function name> (<arg1 type> <arg1 name>, <arg2 type> <arg2 name>, ... )
{
// Function code
}

Explanations of the various fields of the function declaration are as follows:

<return type> - Specifies the data type of the result returned by the function. If the function does not return a result then void should be specified. Unless otherwise specified, functions are assumed to return an int.

<function name> - The name assigned to the function. This is the name by which the function will be referenced when it is called from within the application code. Note that, unless otherwise specified using the static specifier, function names are global and must be unique within the context of an application to avoid compilation errors.

<argn type> - The type of the argument passed through to the function.

<argn name> - The name by which the argument is to be referenced in the function code.

Function code - The code of the function that does the work.

As an example, the following function takes no arguments, returns no result and simply displays a message:

void sayhello ()
{
      NSLog (@"Hello");
}

The following sample function, on the other hand, takes two integer arguments and returns the result of a multiplication of those numbers:

int multiply (int x, int y)
{
     return x * y;
}

The main() Function

This is a special function name that tells the Objective-C compiler where to start program execution.

int main (int argc, const char * argv[])
{
   @autoreleasepool {
    // Code here
   }
   return 0;
}

Calling an Objective-C Function

Functions are called using the following syntax:

<function name> (<arg1>, <arg2>, ... )

For example, to call a function named sayhello that takes no arguments and returns no value, we would write the following code:

sayhello();
To call a function called multiply that take two arguments and returns an integer we might write the following code:

int result;

result = multiply (10, 20);

Function Prototypes

Where a function is declared in relation to where it is called from is a significant factor. A compiler reads an Objective-C source file from top to bottom. If the compiler comes across a call to a function before it has found the function declaration it has to make assumptions about the type of result that function returns.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        float result;

        result = multiply( 10, 20 );
    }
    return 0;
}

float multiply (int x, int y)
{
        return x * y;
}

Function Scope and the static Specifier

Objective-C functions are considered by default to be global in scope. This means that a function declared in one file in a program can be called from any other code file in the program.

static float multiply (int x, int y)
{
        return x * y;
}

Static Variables in Functions

In the normal course of program execution, any variables declared locally in a function are discarded when the function exits and execution returns to the code location from where the call was made.

#import <Foundation/Foundation.h>

void displayit (int);

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        int i;

        for (i=0; i<5; i++)
        {
                displayit( i );
        }

   }
   return 0;
}

void displayit (int i)
{
        int y = 0;

        y += i;

        NSLog (@"y + i = %i", y);
}

Methods

Methods are pretty much a lot like functions but the only difference is that they are attached to classes and are defined using a slightly different syntax in Objective-C.

Instance Methods vs. Class Methods

Instance methods can be thought of as actions that can be taken on instances of a class.

An example of an instance method’s syntax:
- (SomeReturnType)instanceMethodName

NSArray *myItems = @[@"Macbook", @"iPhone", @"iPad"];
[myItems objectAtIndex:1];

Class methods are similar; however, they are called on the class itself rather than an instance of the class. So instead of sending a message to an object created from a class we send the message to the class itself.

// Sending a message to the NSArray class
[NSArray array];

An example of a class method’s syntax:
+ (SomeReturnType)classMethodName

Method Arguments

If we want to pass some external data to a method that it can operate on we can do so by passing arguments, similar to how we do in regular functions. The only difference is that the syntax varies slightly.

// person.m
- (void)sayHelloToPerson(Person*)person {
     NSLog(@"Hello there, %@"., person.name);
}

Methods that Take Multiple Arguments

What if we want to create methods that take multiple arguments? It’s really not that difficult.

// Person.m
- (int)addNumbersOne:(int)firstNumber andTwo:(int)secondNumber {
     return firstNumber + secondNumber;
}

Distinguish Between Function and Method Calls

Any easy way to tell if we are calling a function or a method is to look at how it is invoked (fancy programming word for called) in the program. If we see a call with square brackets around it we know that a method is being called, if not it’s a function call.

// Calling a function that adds two numbers
add(1, 2) // 3 would be returned
// Calling a method that adds two numbers
[someObject addNumbers:1 and:2;]; // 3 would also be returned

Happy Objective-C Coding 🙂


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top