Implementing the View Controller Logic
To finish off FieldButtonFun, we need to add the createStory method within the view controller (FieldButtonFunViewController). This method will search the template text for the <place>, <verb>, and <number> placeholders, and then replace them with the user’s input, storing the results in the text view. We’ll make use of the NSString instance method stringByReplacingOccurrencesOfString:WithString to do the heavy lifting. This method performs a search and replace on a given string.
For example, if the variable myString contains Hello town and you wanted to replace town with world, you might use the following:
myNewString=[myString stringByReplacingOccurrencesOfString:@"town" WithString:@"world"];
In this case, our strings are the text properties of the text fields and text views (thePlace.text, theVerb.text, theNumber.text, theTemplate.text, and theStory.text).
Add the final method implementation, shown in Listing 4, to FieldButtonFunViewController.m after the @synthesize directives.
Listing 4.
1: -(IBAction) createStory:(id)sender { 2: theStory.text=[theTemplate.text 3: stringByReplacingOccurrencesOfString:@"<place>" 4: withString:thePlace.text]; 5: theStory.text=[theStory.text 6: stringByReplacingOccurrencesOfString:@"<verb>" 7: withString:theVerb.text]; 8: theStory.text=[theStory.text 9: stringByReplacingOccurrencesOfString:@"<number>" 10: withString:theNumber.text]; 11: }
|
Lines 2–4 replace the <place> placeholder in the template with the contents of the thePlace field, storing the results in the story text view. Lines 5–7 then update the story text view by replacing the <verb> placeholder with the appropriate user input. This is repeated again in lines 8–10 for the <number> placeholder. The end result is a completed story, output in the theStory text view.
Releasing the Objects
When you’re done using an
object in your applications, you should always release it to free up
memory. This is good practice, even if the application is about to exit.
In this application, we’ve retained six objects—each of the interface
elements—that need to be released. Edit the dealloc method to release these now:
- (void)dealloc {
[thePlace release];
[theVerb release];
[theNumber release];
[theStory release];
[theTemplate release];
[generateStory release];
[super dealloc];
}
Our application is finally complete!
Building the Application
To view and test the FieldButtonFun, click Build and Run in Xcode. Your finished app should look very similar to Figure 19, fancy button and all!
This project provided a
starting point for looking through the different properties and
attributes that can alter how objects look and behave within the iPhone
interface. The take-away message: Don’t assume anything about an object
until you’ve reviewed how it can be configured.