SundayMonday
SundayMonday

Reputation: 19727

Objective-C method syntax

I was surprised when the following method definition compiled (using Apple LLVM 4.1):

- (void) testMethod:someArgument {

}

Notice the type of someArgument is missing. What's the rule in Objective-C about specifying the types of method arguments?

Upvotes: 6

Views: 161

Answers (4)

Caleb
Caleb

Reputation: 124997

The Objective-C Programming Language tells us:

For the object-oriented constructs of Objective-C, such as method return values, id replaces int as the default data type. (For strictly C constructs, such as function return values, int remains the default type.)

Upvotes: 1

DrummerB
DrummerB

Reputation: 40211

The default argument type is id. Even this will compile:

- testMethod:someArgument {
}

This is a method that takes an id as its argument and should return an id.

Actually, not even the method name is necessary:

- :someArgument {
}

This can be called as:

[self :someObject];

Of course all of this is very bad practice and you should always specify the types (and the names).

Upvotes: 7

Michael Dautermann
Michael Dautermann

Reputation: 89509

The "type" in the method argument is used for type checking by both the compiler and for run-time message passing.

The way it's being called in your prototype up there, it's the equivalent of an "(id)".

You can find more information in the "Methods can take Parameters" section of Apple's Programming with Objective C document. I also see some very helpfun information in the "Object Messaging" section of "The Objective-C Programming Language" document.

Upvotes: 2

Tomasz Wojtkowiak
Tomasz Wojtkowiak

Reputation: 4920

Language specification states:

If a return or parameter type isn’t explicitly declared, it’s assumed to be the default type for methods and messages—an id.

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/objectivec/chapters/ocDefiningClasses.html

Upvotes: 2

Related Questions