Concise description of how .h and .m files interact in objective c?

Posted by RJ86 on Stack Overflow See other posts from Stack Overflow or by RJ86
Published on 2010-04-11T23:01:55Z Indexed on 2010/04/11 23:13 UTC
Read the original article Hit count: 235

Filed under:

I have just started learning objective C and am really confused how the .h and .m files interact with each other. This simple program has 3 files:

Fraction.h

 #import <Foundation/NSObject.h>
    @interface Fraction : NSObject {
        int numerator;
 int denominator;
    }
    - (void) print;
    - (void) setNumerator: (int) n;
    - (void) setDenominator: (int) d;
    - (int) numerator;
    - (int) denominator;
    @end

Fraction.m

 #import "Fraction.h"
    #import <stdio.h>
    @implementation Fraction
    -(void) print { printf( "%i/%i", numerator, denominator ); }
    -(void) setNumerator: (int) n { numerator = n; }
    -(void) setDenominator: (int) d { denominator = d; }
    -(int) denominator { return denominator; }
    -(int) numerator { return numerator; }
    @end

Main.m

 #import <stdio.h>
    #import "Fraction.h"
    int main(int argc, char *argv[]) {
        Fraction *frac = [[Fraction alloc] init];
 [frac setNumerator: 1];
 [frac setDenominator: 3];
 printf( "The fraction is: " );
 [frac print];
 printf( "\n" );
 [frac release];
 return 0;
    }

From what I understand, the program initially starts running the main.m file. I understand the basic C concepts but this whole "class" and "instance" stuff is really confusing. In the Fraction.h file the @interface is defining numerator and denominator as an integer, but what else is it doing below with the (void)? and what is the purpose of re-defining below? I am also quite confused as to what is happening with the (void) and (int) portions of the Fraction.m and how all of this is brought together in the main.m file. I guess what I am trying to say is that this seems like a fairly easy program to learn how the different portions work with each other - could anyone explain in non-tech jargon?

© Stack Overflow or respective owner

Related posts about objective-c