Thinking in Javascript but writing Objective-C (Xcode/iOS): From function to method

As a teaching exercise let's pretend we want to change a Javascript function into an Xcode method. Here's a simple Javascript function that takes whatever number we send it and returns that number +1:
function addOne(number) {

return number + 1;

}
Now what that would look like in Xcode (Objective-C):
-(int)addOne:(int)number {

return number + 1;

}
The internal statement is the same, and the name of the function/method (addOne) remains the same, as does the instance variable (number), but the punctuation has changed, 'function' has gone and those two (int) things are new. The first two things shouldn't worry you at this stage.

The (int)s, however, should worry you. They exist because with Xcode we have to tell it explicitly what a method is going to receive and what it is going to send back, whereas in Javascript we can send anything to a function and receive anything back. (Whether or not the Javascript will run successfully with what we send it is a different matter.)

The (int) is an abbreviation of integer, so Xcode will not complain as long as we send the method an integer and process anything we receive back as an integer as well.

It can of course be any class of object that we send to a method and any class - and not necessarily the same - that we receive back, but let's keep it simple for now.

So how do we test that the Javascript function and the Xcode method really do the same thing. Here's a couple of rough and ready ways of testing. First the Javascript in a simple HTML file:
<html>
<script>
function addOne(number) {

return number + 1;

}

document.write("Your returned number is " + addOne(1));
</script>
</html> 
Open this in a web browser you should see the result.

To test this in Xcode we need to replace the code in the primary View Controller with this (note: when creating the project either enter the word "function" in the Class Prefix box or change "functionViewController.h" in the code to the name of your primary view controller's header file):


#import "functionViewController.h"

@interface functionViewController ()

@end

@implementation functionViewController

-(int)addOne:(int)number {
    
    return number + 1;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    int returnedNumber = [self addOne:1];
    NSLog([NSString stringWithFormat:@"Your returned number is %d", returnedNumber]);
   
}

@end
Running this and inspecting the console you should see the same result that was in your web browser. If we didn't want to see the result and we simply stripped back the code to the calling of the function without everything else in the file then the Javascript would look like this:

addOne(1); 
and the Objective-C like this:
    [self addOne:1];
    

Comments