Passing Pointers to Functions in Objective-C
Last Updated :
17 Mar, 2023
Pointers are a crucial aspect of any programming language and passing pointers to functions in Objective-C is no exception. In Objective-C, pointers are used to pass values between functions and to manipulate memory in a more flexible manner. Pointers can be passed as arguments to functions and can also be returned as function results.
Passing pointers to functions in Objective-C can help you in optimizing the memory utilization of your code, reduce the number of function calls, and improve the overall performance of your code. In this article, we will discuss how to pass pointers to functions in Objective-C, understand the different types of pointer arguments, and see some examples to get a better understanding of the concept.
Types and Subtypes of Pointers
Objective-C, pointers can be of two types: constant pointers and non-constant pointers.
- Constant Pointers: When a pointer is declared as a constant, its value cannot be changed.
- Non-Constant Pointers: When a pointer is not declared as a constant, its value can be changed.
Similarly, pointers can also be of two subtypes: input pointers and output pointers.
- Input Pointers: Input pointers are used to pass values into a function.
- Output Pointers: Output pointers are used to return values from a function.
Syntax:
The syntax for passing pointers to functions in Objective-C is as follows:
-(void) sampleFunction:(int *) inputPointer;
-(int *) sampleFunctionOutput;
Here, inputPointer is the input pointer, and sampleFunctionOutput is the output pointer. The * symbol is used to declare a pointer in Objective-C.
Example 1: In this example, we are going to understand how to pass pointers to a function.
ObjectiveC
#import <Foundation/Foundation.h>
@interface SampleClass : NSObject
-( void ) sampleFunction:( int *) inputPointer;
@end
@implementation SampleClass
-( void ) sampleFunction:( int *) inputPointer
{
*inputPointer = 20;
}
@end
int main()
{
int sampleValue = 10;
int *inputPointer = &sampleValue;
SampleClass *obj = [[SampleClass alloc] init];
[obj sampleFunction:inputPointer];
printf( "Value after passing to function: %d\n" , sampleValue);
return 0;
}
|
Output:
Value after passing to function: 20
Example 2: In this example, we are going to understand how to return Pointer from Function.
ObjectiveC
#import <Foundation/Foundation.h>
@interface SampleClass : NSObject
-( int *) sampleFunctionOutput;
@end
@implementation SampleClass
-( int *) sampleFunctionOutput
{
static int sampleValue = 30;
return &sampleValue;
}
@end
int main()
{
SampleClass *obj = [[SampleClass alloc] init];
int *outputPointer = [obj sampleFunctionOutput];
printf( "Value from function: %d\n" , *outputPointer);
return 0;
}
|
Output:
Value from function: 30
Share your thoughts in the comments
Please Login to comment...