O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.3. Methods

Now you are going to take a closer look at how methods are defined, and called, or invoked, to be more consistent with the OO terminology.

Consider the first method of the Person class above:

-(id)initWithName:(NSString *)name andAddress:(NSString *)address;

The method's name is broken into two segments, initWithName: and andAddress:. The full name of this method is initWithName:andAddress:, which is quite a mouthful, but has the advantage that it reads like a sentence. After each section of the name, there is a colon, which is actually considered part of the name itself, and then a parameter. The type of the parameter is given in parentheses, followed by the parameter name.

It is also legal to have parameters with only a colon, and no preceding label, like this:

-(void)methodWith3Parameters:(NSString *)param1 :(float)param2 :(int)param3;

The method name in this case is methodWith3Parameters:::—the colons are significant.

The parameter types in a method declaration are also optional, but if you exclude them, the parameter is assumed to be an object. A generic object has the type id in Objective-C, as shown in the following method declaration:

-(void)doSomethingWithObject:(id)object1 andObject:(id)object2;

This is an equivalent declaration:

-(void)doSomethingWithObject:object1 andObject:object2;

By now you will have realized that Objective-C methods also have return values, just like C functions. In the first example in this section, the return value was of the type ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required