Is it correct to write objective-c method like this
-methodA: (NSString *)str // without return type
{
return @"test";
}
Above method is working fine for me.
Is -methodA: (NSString *)str
same as -(id)methodA: (NSString *)str
?
I am using Mac 10.5 os x
sdk.
In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
To answer your question, from "The Objective-C 2.0 Programming Language":
If a return or argument type isn’t explicitly declared, it’s assumed to be the default type for methods and messages — an
id
.
So - methodA:(NSString *)str
is valid and the same as - (id)methodA:(NSString *)str
.
However having said that it is certainly unusual coding practice and not to be encouraged - type the extra four characters!
- (void) methodA (NSString *)str //always start a methodod name lower case
{
return; //If you do not return anything then there is nothing to return.
}
(id)
is different from (void)
. You will have to return somthing here. id
represents an object of any type. Only void
represents 'nothing'.
It is allowed, as 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
.
I changed -init in my app:
-init
{
...
return self;
}
and compiler did not show any warning, and if I change -init like that:
-(int)init
{
...
return 0;
}
compiler shows warning about expected type, so I could say -init and -(id)init are the same methods, since I did not even know that compiler would pass this syntax and since checking language's features like that is bad practice :). I will read Apple's docs about Objective-C and try to find out something about that. Thanks for nice question :)
EDIT:
wow, you can read docs here, chapter Class Interface. (void), (NSObject*) and etc are only casts. Quote: "Method return types are declared using the standard C syntax for casting one type to another". And another quote: "If a return or parameter type isn’t explicitly declared, it’s assumed to be the default type for methods and messages—an id".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With