6

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?

4 Answers 4

7

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting! I like Objective-C even more knowing -:v{} compiles :-)
I refuse to answer any questions that use methods like that :-D
And if you're looking for the shortest method that compiles, it's probably -a{} ;-)
2

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

Comments

2

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.

Comments

1

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.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.