Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c method without return type

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.

like image 251
Parag Bafna Avatar asked Sep 04 '12 09:09

Parag Bafna


People also ask

Which return type cannot return any value to caller function?

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.


4 Answers

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!

like image 125
CRD Avatar answered Sep 19 '22 16:09

CRD


- (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'.

like image 29
Hermann Klecker Avatar answered Sep 22 '22 16:09

Hermann Klecker


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.

like image 22
hamstergene Avatar answered Sep 20 '22 16:09

hamstergene


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

like image 22
medvedNick Avatar answered Sep 22 '22 16:09

medvedNick