The Objective-C 2.0 Programming Language

I’ve been playing around with iPhone development and I have to say — I love the Objective-C 2.0 Programming Language. It’s got all the simple goodness of C but with very nice OOP extensions. I’m not sure to what extent, if any, it’s used besides in the Appleverse, but it’s nice and I like it. Here is a tiny example:

1: NSMutableArray *particles = [[NSMutableArray alloc] init];
2: [particles addObject:newParticle];
3: ...
4: Particle *p;
5: for(n=0;n<[particles count]; ++n ) {
6: p = [particles objectAtIndex:n];
7: [p setName:[self ownerName]];

In line 1 we see the Obj-C way of initializing an object. First we send an alloc message to the NSMutableArray class and then send an init message to the object returned by it. We then assign it to a pointer variable of the appropriate type. In line 2 we add a new object newParticle to the particles array. Later, at line 4 we create a C-style pointer to a Particle object and in line 5 we find out the number of objects in the array particles by sending it a count message. In line 6 we pull out a specific object from the array and in line 7 we send the setName message to our Particle object (the normal “setter” for the instance variable name) and send as a parameter the value from the “getter” of the class we are in (self) for the instance variable ownerName.

You can see there is an odd mix of traditional C and object stuff.

It’s also quite flexible. For example, if you have an instance variable named isEnabled you can refer to that variable in 3 different ways:

isEnabled = NO;
self.isEnabled = NO;
[self setIsEnabled:NO];

In the first two we access the variable directly and in the third we call the setter method. As we saw in lines 1 and 7 above, you can nest these as much as you like.

self.currentParticle.size = 10;
[[self currentParticle] setSize:10];

But at any time you can whack in some normal ol’ C:

size = (sizeFactor *2.0*arc4random() / (float)UINT_MAX)+sizeFactor;

Pretty cool.

The Objective-C 2.0 Programming Language