Methods, and instances in Objective-C. (Part 2)

In our last objective-c tutorial we tackled the @interface section; this tutorial we are going to tackle the @implementation section. This part of the a program is where you tell the complier what we wrote in the @interface section mean. (To see the whole tutorial on that click here.) For example in our @interface section in our last tutorial we wrote:

@interface Fraction : NSObject

{

int num;

int dem;

}
-(void) print;

-(void) setNum: (int) n;

-(void) setDem: (int) d;

@end

In the @implementation section we are going to actually tell the complier what -(void) print; and the other method (and method arguments) mean. Lets start actually writing the @implementation section. I’m going to show you the whole @implementation section and then I will explain it.

@implementation Fraction: NSObject

-(void) print

{

NSLog(@”%i/%i”, num, dem);

}

-(void) setNum: (int) n

{

num = n;

}

-(void) setDem: (int) d;

{

dem = d;

}

@end

So lets start with the  beginning. You will always start this section off saying “@implementation Class”. For our example we ill say “@implementation Fraction”.  You will always put the class name right after @implementation. If you do not do that the complier will give you an error saying “Hey what class are you talking about?!” After that you can see in our full example above I added NSObject after the class name. You dont have to do this, I did it for good practice and to remind myself what superclass we are working with here. After you declare that we are working in the @implementation section we can actually tell the complier what our methods are going to do. This makes it much easier with things like telling the program to display NSLogs. You can type the method name instead of actually writing out the code in the program section. In the program section you could just type “[myFraction print];” instead of typing out “NSLog(@”Your fraction is:%i/%i, num, dem). More on what that actually means in our third part of our tutorial series. So that is exactly what we type here giving it the print name. Then below that you see

-(void) setNum: (int) d;

{

dem = d;

}

The setNumerator: method stores the integer argument you called n in the instance variable numerator. Similarly, setDenominator: stores the value of its argument d in the instance variable denominator. We are just setting dem equal to d. Similar to setNum. As we did for the last section we are going to end this with the @end. Thats it for this tutorial. Part 3 should be up by monday or tuesday.

Popularity: 15% [?]

You can leave a response, or trackback from your own site.
blog comments powered by Disqus