Jonathan Pepin

Declare a class in Objective-C

2013-08-10

Yesss I started to learn Objective-C. As usual, I will try to write about what I learn here, starting from the very basic, and hopefully writing some more interesting stuff sooner or later!

Something really confusing coming from Ruby, or some other higher programming language, is the need of two files to declare a class.
The first file is the header, or interface file. It declares the instance variables and methods.
The second file is the implementation file. It implements each methods.

Dinosaur.h

First, as explained, the interface file. This is pretty simple and straight forward, it declares the instance variables and the methods. Few points might require clarification tho.

@interface Dinosaur : NSObject
This says the file is the interface class, and declares the class as being Dinosaur, which inherits from NSObject.

Between the curly braces is the instance variables declaration.

@property is to generate setters and getters for the instance variables.
Let me explain.
When you create an instance of an object, in that case an new dinosaur, you will want to set its weight and its numOfLegs, right? Well, the method that you would create for that is called a setter.
And after setting some values for those instance variable, you might want to access them to read them, or use them for other methods- this would be the getter.
So @property float weight will imply 2 methods:

- (void)setWeight:(int)w;
- (int)weight;

The last part is simply declaring a method that this object has, which is rawr, which returns a string.