Wednesday, April 28, 2010

Quick Objective-C example

In this example we will see how to send multiple parameters to a method and how to create a conscructor method inside a class.


Create a new project in xcode and name it example2.
Now, create a new class named TestClass.

TestClass.h


Two variables are created: testVariable1 and testVariable2.

Two methods are also created.


TestClass.m


main.m


The first method is used to receive two parameters and assign them to their respective variables. The name of the method is extended for it to accommodate various parameters. The full name of this method is " setTestVariable1:and2: ". The part of the name after the first colon could be omitted in the declaration but it is recommended to use it since it gives us some insight about what kind of parameter the function needs to receive.

The " print " method is used to print the results of the two variables.

Let's test this to check that we did everything right.
Compile your project by pressing "Command + B" on Xcode. Press "Command + Shift + R" to open the Console and "Command + R" to Run your application.


Now we'll add a constructor method to this example. 
A constructor method lets you initialize the variables in an object at the same time that the object is initialized.


TestClass.h




TestClass.m



The name of the constructor method is initWithTestVariable1:and2:.This method initializes itselft, and then assigns values to its variables using the same method we used at the beginning of this example(setTestVariable1:and2:).


main.m


Run this again to test it.




The constructor method is used instead of init on the first statement. By doing this, the values of testVariable1 and testVariable2 are assigned in the same statement where the object is initialized.

No comments:

Post a Comment