Objective-C method syntax

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

- (void) testMethod:someArgument { } 

Note that someArgument missing. What rule in Objective-C indicates the type of method arguments?

+6
source share
4 answers

The default argument type is id . Even this compiles:

 - testMethod:someArgument { } 

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

Actually, even the method name is not required:

 - :someArgument { } 

It can be called:

 [self :someObject]; 

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

+7
source

The "type" in the method argument is used to check the type both by the compiler and to send messages at run time.

As it is called in your prototype there, it is the equivalent of " (id) ".

For more information, see "Methods may take parameters" in Apple Programming with the Objective-C Document . I also see some very useful information in the "Object Messages" section of the Objective-C Documentation Programming Language .

+2
source

The language specification states:

If the return type or parameter type is not explicitly declared, it is assumed to be the default type for methods and messages - identifier.

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

+2
source

The Objective-C programming language tells us :

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

+1
source

Source: https://habr.com/ru/post/926675/


All Articles