Open In App

Functions in Objective-C

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. It is the main programming language used by Apple for the OS X and iOS operating systems and their respective application programming interfaces (APIs), Cocoa and Cocoa Touch.

One of the features of Objective-C is that it supports functions, which are named blocks of code that can be called upon to perform a specific task. Functions can be provided with data on which to perform the task and can return a result to the code that called them. Functions can help to organize the code, avoid repetition, and improve readability and maintainability.

Defining and Declaring a Function

A function definition in Objective-C consists of two parts: a function header and a function body. The function header specifies the name, return type, and parameters of the function. The function body contains a collection of statements that define what the function does.

Syntax:

return_type function_name(parameter_list)

{

// body of the function

}

Example:

Below code defines a function called max that takes two integers as parameters and returns the maximum between them:

int max(int num1, int num2)

{

int result;

if (num1 > num2)

{

result = num1;

}

else

{

result = num2;

}

return result;

}

A function declaration tells the compiler about the name, return type, and parameters of a function. The actual body of the function can be defined separately. A function declaration has the same syntax as the function header, followed by a semicolon.

For example, the following code declares the max function:

int max(int num1, int num2);

A function declaration is also known as a function prototype. It is usually placed at the beginning of a source file or in a header file. A function declaration is optional, but it is recommended to declare a function before using it to avoid compiler errors or warnings.

Calling a Function

To call a function, we use the function name followed by a pair of parentheses enclosing the arguments (if any). The arguments are the values that are passed to the function when it is invoked. The arguments must match the number and type of the parameters declared by the function.

For example, the following code calls the max function with two arguments:

int a = 10;

int b = 20;

int c = max(a, b); // c will be assigned 20

When a function is called, the control passes from the calling code to the function body. The function executes its statements and returns a value (if any) to the calling code. The control then resumes from where it left off in the calling code.

Passing Arguments and Return Values

There are two ways of passing arguments to a function, By value and By reference.

  1. Passing by value means that a copy of the argument is passed to the function, so any changes made to the argument within the function do not affect the original value.
  2. Passing by reference means that a pointer to the argument is passed to the function, so any changes made to the argument within the function affect the original value.

By default, Objective-C passes arguments by value. To pass an argument by reference, we use an asterisk (*) before the parameter name in both the function declaration and definition. We also use an ampersand (&) before the argument name when calling the function.

For example, the following code defines and calls a function called swap that swaps two integers by passing them by reference:

ObjectiveC




// Objective-C program to pass arguments
// and return values
#include <stdio.h>
 
// Function declaration
void swap(int *x, int *y);
 
// Function definition
void swap(int *x, int *y)
{
  int temp;
   
  // temp gets the value pointed by x
  temp = *x;
     
  // x gets the value pointed by y
  *x = *y;  
     
  // y gets the value stored in temp
  *y = temp;
}
 
// Driver code
int main()
{
  // Function call
  int a = 10;
  int b = 20;
 
  printf("Before swap: a = %d, b = %d\n", a, b);
  swap(&a, &b);
   
  printf("After swap: a = %d, b = %d\n", a, b);
  return 0;
}


Output:

Output

Function Returning Value

A function can return only one value to its caller. The return type of a function must match the type of value returned by it. To return a value from a function, we use the return keyword followed by the value or expression to be returned.

For example, the following code defines and calls a function called square that returns the square of an integer:

ObjectiveC




// Auther: Nikunj Sonigara
 
#include <stdio.h>
 
// Function declaration
int square(int x);
 
// Function definition
int square(int x)
{
    return x * x; // return the square of x
}
 
int main()
{
    // Function call
    int a = 5;
    int b = square(a);
 
    printf("The square of %d is %d\n", a, b);
 
    return 0;
}


Output:

Output

Function Not Returning Value

Some functions do not return any value to their caller. In this case, the return type of the function is the keyword void. A function with a void return type can use the return keyword without any value to exit the function.

For example, the following code defines and calls a function called printHello that prints “Hello, world!” to the standard output and does not return any value:

C++




// Auther: Nikunj Sonigara
 
#include <stdio.h>
 
// Function declaration
void printHello(void);
 
// Function definition
void printHello(void)
{
    printf("Hello, world!\n");
    return; // optional, as it's not needed here
}
 
int main()
{
    // Function call
    printHello(); // prints "Hello, world!"
 
    return 0;
}


Output:Output

Differentiating Between Functions and Methods

In Objective-C, there is a distinction between functions and methods. Functions are code blocks that are unrelated to an object or a class, just inherited from C. Methods are code blocks that are attached to a class or an instance (object) and are invoked by sending messages to them.

The syntax for defining and calling functions and methods is different. Functions use the standard C syntax, as shown in the previous sections. Methods use a special Objective-C syntax, as shown in the following example:

// Method declaration in interface section

– (return_type)method_name:(parameter_type)parameter_name;

// Method definition in implementation section

– (return_type)method_name:(parameter_type)parameter_name

{

// body of the method

}

// Method call by sending a message to an object or a class

[receiver method_name:argument];

Explanation:

  • The sign before the method name indicates that it is an instance method, which means that it can be called by an instance of a class.
  • The + sign indicates that it is a class method, which means that it can be called by a class name.
  • The method name consists of one or more parts separated by colons.
  • Each part corresponds to a parameter of the method.
  • The parameter type and name are enclosed in parentheses after each part.
  • The method name and the parameter list together constitute the method signature.
  • The method call is made by sending a message to a receiver, which can be either an object or a class.
  • The message consists of the method name followed by the arguments enclosed in brackets.
  • The arguments must match the number and type of the parameters declared by the method.

For example, the following code defines and calls a method called add that takes two integers as parameters and returns their sum:

ObjectiveC




// Auther: Nikunj Sonigara
 
#import <Foundation/Foundation.h>
 
// Interface section of Calculator class
@interface Calculator : NSObject
 
- (int)add:(int)x to:(int)y;
 
@end
 
// Implementation section of Calculator class
@implementation Calculator
 
- (int)add:(int)x to:(int)y
{
    return x + y;
}
 
@end
 
int main(int argc, const char * argv[]) {
    // Method call by sending a message to an object of Calculator class
    Calculator *calc = [[Calculator alloc] init];
    int result = [calc add:10 to:20];
    NSLog(@"Result: %d", result); // result will be 30
    return 0;
}


Output:

Method

Note that functions and methods can have the same name as long as they have different signatures. For example, we can have both a function and a method called max, but they must have different parameter lists.

Using Built-in Functions from the Objective-C Foundation Framework

The Objective-C foundation framework provides numerous built-in functions that our program can call. These functions perform various tasks such as memory management, string manipulation, mathematical operations, etc. To use these functions, we need to import the appropriate header files that contain their declarations.

Built-in Function

For example, to use the sqrt function that returns the square root of a double value, we need to import the math.h header file:

ObjectiveC




// Auther: Nikunj Sonigara
 
#include <stdio.h>
#include <math.h>
 
int main() {
    double x = sqrt(25); // x will be 5.0
    printf("The square root of 25 is: %lf\n", x);
    return 0;
}


Output:

The square root of 25 is: 5.000000

Macros

Some of these functions are actually macros, which are preprocessor directives that replace a name with a code fragment. For example, the MIN and MAX macros return the minimum and maximum between two values, respectively. To use these macros, we need to import the Foundation.h header file:

ObjectiveC




// Auther: Nikunj Sonigara
 
#import <Foundation/Foundation.h>
 
int main() {
    int x = MIN(10, 20); // x will be 10
    int y = MAX(10, 20); // y will be 20
     
    NSLog(@"x: %d", x);
    NSLog(@"y: %d", y);
     
    return 0;
}


Output:

x: 10
y: 20


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads