Hello World from Objective C

Standard

In this post I will explain how to do a simple Hello World application using Objective C.

I suppose you already know about C/C++ programing languages…And I will start coding with classes and properties…

We wanna do a simple class with some attributes, a Fraction class.

Let’s see how it works:

@interface Fraction : NSObject{
    int numerator;
    int denominator;
}

-(int)numerator;
-(void)setNumerator:(int)  n;
-(int)denominator;
-(void)setDenominator:(int)  n;

-(double)toDouble;
-(void)print;
@end

As a C++ programming language, you have a file to define the attributes and methods and other file to implementation. In objective-c the way to do it are similar, to create a class you want, firstly, to write @interface … and all classes in Objective C inherits from NSObject(Java Object hahah ).

So, the implementation code looks like:

@implementation Fraction

-(int)numerator{
    return numerator;
}
-(void)setNumerator:(int)  n{
    numerator = n;
}
-(int)denominator{
    return denominator ;
}
-(void)setDenominator:(int)  n{
    denominator = n;
}

-(double)toDouble{
    return numerator/(double)denominator;
}
-(void)print{
    NSLog(@"Fraction %i",numerator/denominator);
}

@end

You can check the getters and setters from each attribute of the class… Yeah.. by default(convention maybe) you don’t need to put “getDenominator”, getAttribute, but the set is the same as Java, for example.
If you like Ruby for example, you figure out that ruby has a syntatic sugar to create getters/setters for an attribute. Objective C has a similar notation to do it… It’s a @property. So, our Fraction class will look:

@interface Fraction : NSObject{
    int numerator;
    int denominator;
}

@property  int numerator;
@property  int denominator;

-(double)toDouble;
-(void)print;
@end

and

@implementation Fraction

@synthesize numerator;
@synthesize denominator;

-(double)toDouble{
    return numerator/(double)denominator;
}
-(void)print{
    NSLog(@"Fraction %i",numerator/denominator);
}

@end

If you are a Java/C/C++ programmer you will feel that Objective-C is so different, but maybe with a time we can get used.