You can declare a method in objective-c and name each parameter twice, basically.
I get the idea that this is powerful, but I'm not quite sure how to use it yet…
When John Greets Kelly:
[ p Greet:"John" toPerson:"Kelly" greetWith:"hey babe" ] ;
Something about it doesn't read naturally. I'm not sure if that's how an experienced objective-c programmer would write that "message".
Can someone explain the reason for two names for each parameter and possibly a more useful example of how this can be used effectively to put meaning in the program?
Also something bothers me and that is the name of the first parameter is basically the same as the name of the 'message'. How do you resolve that in writing meaningful and understandable method/'message names'?
#import <Foundation/Foundation.h> @interface Person : NSObject { } -(void)Greet:(char*)from toPerson:(char*)to greetWith:(char*)greeting ; @end @implementation Person -(void)Greet:(char*)from toPerson:(char*)to greetWith:(char*)greeting ; { printf( "%s says %s to %s\n", from, greeting, to ) ; } @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Person * p = [ Person alloc ] ; [ p Greet:"John" toPerson:"Kelly" greetWith:"hey babe" ] ; [ p Greet:"Kelly" toPerson:"John" greetWith:"get bent" ] ; [ p release ] ; [pool drain]; return 0; }
Best Answer
First things first: as a stylistic note, bring your braces together:
should be
I also note that you're forgetting to initialize Person when you alloc it, you should be using:
Getting the feel for how to declare methods takes a little bit of time. Examining how the framework names its methods is useful. For your specific example, I think you're overengineering. You're looking for something like this:
Notice that I've not capitalized the
g
ingreetPerson
, either. That's a stylistic convention of Objective-C.Don't forget that an object has its own identity, so rarely do you need to instruct an object (meant to represent a person) who it is before it talks to someone. When you write a message, it should read like English. When you get into multiple arguments -- admittedly, rare -- start thinking with commas:
See how that flows? And even that leaves some to be desired, I don't have this mastered yet either. Give it time.
A very useful document on this is Apple's Coding Guidelines for Cocoa.
Also, get yourself out of the C trap. Here's how I'd write your entire program (I'm introducing a boatload of concepts, so don't expect to understand all of it):
This code is completely untested, so if it works without a hitch I'll be duly impressed.