Saturday, December 18, 2010

Explanation of method headers in objective-c (for beginners)

This is a short explanation for beginners coming from other languages like Java or PHP to show how classes are instantiated and how methods are called and defined.

To define a method in programming languages you usually have 3-4 Parts:

1.) Keyword to say that you are about to implement a method (e.g. function)
2.) What kind of object will the method return or void if nothing
3.) The method name
4.) Parameters

Lets say we have a class called calculator.
In this class we want to implement a method called increment. This method gets an integer and returns the integer incremented by one.
This method would look in php like this:

function increment($prmInt){
   return $prmInt++;
}

In objective-c the same method would look like this:

-(int)increment:(int)intSomeNumber{
   return intSomeNumber++;
}

"-"   is equal to the word "function" and tells the compiler that a method starts
"(int)"   defines what will be send back by the method (void if nothing)
"increment"   this is the method name
":"   tells the compiler that a parameter starts
"(int)intSomeNumber"   type and name of parameter

If you want to create a method with several parameters you can just add ":" and some text at the end.
Some examples:

-(void)doSomething:(NSString*)strParameter1 andEvenMoreParameters:(NSString*)strParameter2;
-(void)aMethodWithoutTextbetweeenParameters:(int)i1:(int)i2:(int)i3;

To call these methods you have to instantiate the class:

Calculator* calc =  [[Calculator alloc] init];

now you have allocated an object. With this object you can call the declared method:


int intNumber = 5;
intNumber = [calc increment:intNumber];

and for completeness' sake:

[calc doSomething:@"string1" andEvenMoreParameters:@"string2"];
[calc aMethodWithoutTextbetweeenParameters:1:2:3];

As we don't need the object anymore we will release it so that the memory gets freed:

[calc release];

Cheers

JayEs

No comments:

Post a Comment