Saturday, November 22, 2008

Objective-C

In a glance, Objective-C is C plus object orientation and other fun little things.

Now being used to Java and C# for the last couple of years, this of course means one thing that I personally forgot very happily... pointers. But let's take it step by step.

Files and Headers

An Objective-C file has the file ending ".m", the header file has the file ending ".h"

To include the header files into your coding (be it source or other header files) you'll have to write "#import " for global headers (e.g. Cocoa.h) or "#import "headername.h"" for your own local headers. Besides the name (import <-> include) this is pretty much as in C++ (at least how I remember it :-) )

So starting of with, you would include the framework header file in your header file and your header file in your source file.

How Headers are setup

A header file normally includes an import for other headers and a class definition. The class definition consists out of the class name, its deriving object, its variables and its methods.

A simple class definition could look like this:


@interface AppController : NSObject {

int x;

}

@end

Now this class definition would not do to much as it does not have any methods, but it would define a class named "AppController" being derived from NSObject with one integer variable called x.


The definition always starts with "@interface" and ends with "@end"


A method definition in Objective-C will be defined like this:


- (int) setX:(int)y;


This defines a method setX with a return value of type int. To call the method you'll need to pass a variable of type int which can be accessed by the name y. The "-" in front of the method declaration is not a typo, but tells you that this is a "regular" instance method. A global class method would be defined with a "+" instead (comparable with the "static" keyword of Java/C#). The method definition will not be inserted into the curly brackets but between their end and the "@end" so the new class definition would look like this:


@interface AppController : NSObject {

int x;

}


- (int) setX:(int)y;


@end


The source file


To finish off our example here we'll have a quick look at the corresponding source file:


#import "AppController.h"

@implementation AppController


-(int) setX:(int)y

{

//Magic happens here.....

x=y;

return x;

}

@end

This should not be to much of a suprise now. Pretty much straight forward besides the "@implementation" and "@end" commands which simply wrap up the class related coding.

No comments: