0

Both of the following seem to return, so is there a reason to use return in methods?

- (void)goDoIt {  
  [self doSomething];
  [self doSomethingAndReturn];
}

- (void)doSomething {
  // just visiting
}

- (void)doSomethingAndReturn {    
  return; // returning now 
}

Is there any difference?

jscs
  • 63,694
  • 13
  • 151
  • 195

4 Answers4

2

"return" is generally used to send data back not to tell the program to return to the position from which the function was called.

The (void) in front of the function name tells us that the function is not expected to return anything after it finished running. If for instance you want a function to calculate a number then you would write (int) for integer instead of (void). Then the function needs to contain at least one return statement. Like: "return result;"
A function can have multiple return statements that end the function and return a value. In a void function the return statement can be used to end the function execution early, otherwise there is no need for a return statement in a void function.

Read more about objective-c functions here: Tutorials Point

andrbmgi
  • 528
  • 3
  • 17
1

In a method defined with a return type, obviously return is necessary. In methods or functions defined to return nothing (void) they are not necessary. Yet they offer one way to prematurely end a method. For example:

- (void)myMethod {
    //doing some things here
    if (myVariable < 2) {
        // done here
        return;
    }
    // the following will only be run if myVariable is larger than 1
   }
Volker
  • 4,640
  • 1
  • 23
  • 31
0

One objective-c is object oriented. Functions are a concept in procedural programming. Object oriented uses methods instead. All of your examples do the same thing since they return void. If your method needed to return variable then you would have to put a return statement.

-(int)someMethod
{
//code executed
return 5;
// code after return not executed
}
0

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method like:

void doSomething(int a) {
    if (a == 0) {
       //do something
       return;
    }
    //Otherwise, do something
}

So , if (a == 0) is true, then the code written after the return statement will not execute , else the code written outside the if block will execute.

If you try to return a value from a method that is declared void, you will get a compiler error.

Arjit
  • 3,290
  • 1
  • 17
  • 18