Tuesday, February 20, 2007

Paradigm shift

Moving into Objective-C with Cocoa requires a whole paradigm shift when talking about OOP. Rather than objects having methods, they respond to messages. And rather than calling methods, you send messages. The interesting thing is you can send any message you want to an object, the question is they may not respond. Take the following class:


#import

@interface MyClass : NSObject
{
NSString * name;

NSMutableArray *items;
}

- (void)setName:(NSString *)aName;

@end



Lets assume I've implemented the rest of this. The following code will compile




MyClass * test = [[MyClass alloc] init];

[test someMethod];



Now, notice that there is not a method called "someMethod" in the class MyClass, however I'm still able to "call" it in my source and compile it. The reason is, I'm not really calling "someMethod", but rather sending a message. When this runs it throws an exception but thats still very different than other languages I'm use to. One cool thing is you can ask an object if it would respond to a message before sent. A model that is very much like inspection in Java.

No comments: