Difference Between Method and Function in Objective-C
Q: What is the difference between a method and a function in Objective-C?
- Objective C
- Junior level question
Explore all the latest Objective C interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Objective C interview for FREE!
In Objective-C, a method is a function that is associated with an object, whereas a function is a stand-alone unit of code that can be called from anywhere in your program.
Here are the main differences between methods and functions in Objective-C:
1. Method:
- A method is associated with an object, and is called on that object using the dot notation or square bracket notation.
- A method is defined inside the interface and implementation of a class.
- A method can access the properties and instance variables of the object it belongs to.
- A method can be overridden in a subclass.
- A method can be declared as private or public.
Here's an example of a method:
@interface MyClass : NSObject @property (nonatomic, strong) NSString *myString; - (void)myMethod; @end @implementation MyClass - (void)myMethod { NSLog(@"Hello, world! %@", self.myString); } @end
In this example, "myMethod" is a method of the "MyClass" class that prints "Hello, world!" along with the value of the "myString" property.
2. Function:
- A function is a stand-alone unit of code that can be called from anywhere in your program.
- A function is defined outside of any class or interface.
- A function cannot access the properties or instance variables of an object.
- A function cannot be overridden.
- A function has global scope by default.
Here's an example of a function:
NSString* myFunction(NSString* inputString) { return [NSString stringWithFormat:@"You entered: %@", inputString]; }
In this example, "myFunction" is a stand-alone function that takes an NSString input and returns another NSString with the input string formatted in a specific way.
In summary, methods are associated with objects and can access their properties and instance variables, while functions are stand-alone units of code that can be called from anywhere in your program but cannot access object properties.


