Objective C Methods by Example
Methods are similar to functions in C. There are two types of methods.
- Class Method
- Instance Method
Class Method
Class methods can be accessed directly without object instantiation. A sample class method is shown below.
@interface SampleClass:NSObject /* Class method begins with + sign. Return type follow in bracket. We then have the method name Next we have optional parameter */ + (void)sampleClassMethod; @end @implementation SampleClass + (void)sampleClassMethod{ NSLog(@"Class method"); } @end int main(int argc, const char * argv[]) { // Autoreleasepool used in main for automatic memory management. @autoreleasepool { [SampleClass sampleClassMethod]; } return 0; }
Instance Method
Instance methods can be accessed only with objects. A sample is shown below.
@interface SampleClass:NSObject /* Instance method begins with - sign. Return type follow in bracket. We then have the method name Next we have optional parameter */ - (void)sampleClassMethod; @end @implementation SampleClass - (void)sampleClassMethod{ NSLog(@"Class method"); } @end int main(int argc, const char * argv[]) { // Autoreleasepool used in main for automatic memory management. @autoreleasepool { SampleClass *sampleClass = [[SampleClass alloc] init]; [sampleClass sampleClassMethod]; } return 0; }
Methods with arguments
Methods can take multiple parameters. A sample is shown below.
@interface SampleClass:NSObject /* Instance method begins with - sign. Return type follow in bracket. You then have the method name Next you have optional parameters You can see withNumber2: is the joining word making it more readable while accessing the method */ - (void)addNumber1:(int) number1 withNumber2:(int) number2; @end @implementation SampleClass - (void)addNumber1:(int) number1 withNumber2:(int) number2{ NSLog(@"The sum is %d",number1+number2); } @end int main(int argc, const char * argv[]) { // Autoreleasepool used in main for automatic memory management. @autoreleasepool { SampleClass *sampleClass = [[SampleClass alloc] init]; [sampleClass addNumber1:10 withNumber2:20]; } return 0; }
You can see in the above program how we define method with multiple arguments. You can see there is a joining word second parameter onwards to make it more readable.