I’ve finally got round trying some Objective C programming beyond outputting “hello world” with what is in effect ANSI C. I’m coming from a Perl background with a a smattering of other experience such as ANSI C, ASP and PHP all a looooong time ago. I recently read through a couple of Ruby texts which were very good, but to be honest I couldn’t find a reason to stop using Perl and start with Ruby. It did give me a good course on Object Oriented programming, which as you would expect by the name, Objective C is. I’m using “Programming in Objective-C” by Stephen G. Kochan as my text, lets hope its a good as the Llama book was for Perl. The first two chapters are pretty much background, but by the end of Chapter 3 there is a worthwhile exercise to which is to define a class, create an objet from the class, use it and get rid of it. Here’s my first stab, so stand by…
#import // INTERFACE SECTION @interface XYPoint: NSObject { int x; int y; } -(void) print; -(void) setX: (int) xentry; -(void) setY: (int) yentry; @end // IMPLEMENTATION SECTION @implementation XYPoint -(void) print; { printf("%i,%i", x,y); } -(void) setX:(int)xentry { x=xentry; } -(void) setY:(int)yentry { y=yentry; } @end int main (int argc, const char * argv[]) { @autoreleasepool { XYPoint *myXYP = [[XYPoint alloc] init]; [myXYP setX:20]; [myXYP setY:30]; printf("The coordinate is :"); [myXYP print]; printf("\n"); } return 0; }
Incredibly it compiles and runs without error! The output is:
The coordinate is :20,30 Program ended with exit code: 0
I’m using Xcode 4 after a brief battle with it described in an earlier post. It’s very complicated with a lot of stuff that I certainly don’t need to write Objective-C programs, but the consensus of opinion seems to be that its worth the learning curve to use.