Changes

Jump to: navigation, search

Creating an Interactive iPhone App

2,205 bytes added, 14:22, 1 April 2010
Adding Actions and Outlets
.
</pre>
 
Before we proceed it is probably a good idea to pause and explain what is happening in the above code. Those already familiar with Objective-C, however, may skip the next few paragraphs.
 
In this file we are implementing the <tt>convertTemp</tt> method that we declared in the .h file. This method takes as a single argument a reference to the sender. The ''sender'' is the object that triggered the called the method (in this case our button object). Whilst we won’t be using this object in the current example, this can be used to create a general purpose method in which the behavior of the method changes depending on how it was called. We could, for example, create two buttons labeled ''Convert to Fahrenheit'' and ''Convert to Celsius'' respectively, each of which calls the same <tt>convertTemp</tt> method. The method would then access the sender object to identify which button triggered the event and perform the corresponding type of unit conversion.
 
Next, the code declares a variable of type double in order to handle the fact that the user may have entered a floating point value. We then use dot notation to access the <tt>text</tt> property (which holds the text displayed in the text field) of the <tt>UITextField</tt> object. This property is itself an object of type <tt>NSString</tt>. The NSString object has a method, named <tt>doubleValue</tt> that converts the string value to a double. We therefore call this method on the text property and assign the result to our <tt>farenheit</tt> variable.
 
Having extracted the text entered by the user and converted it to a number we then perform the conversion to Celsius and store the result in another variable named <tt>celsius</tt>. Next, we create a new <tt>NSString</tt> object and initialize it with text that comprise the word Celsius and the result of our conversion. In so doing, declare a pointer to this new object and call it <tt>resultText</tt>.
 
Finally, we use dot notation to assign the new string to the text property of our <tt>UILabel</tt> object so that it is displayed the user. The last step releases the memory that was allocated to the object referenced by <tt>resultText</tt> since it is no longer needed.
We also need to modify the <tt>viewDidUnload</tt> and <tt>dealloc</tt> methods in this file to make sure we properly release the memory we allocated for our variables. Failure to do so will result in a memory leak in our application:

Navigation menu