Documentation Archive Developer
Search

Troubleshooting and Reviewing the Code

If you are having trouble getting your app to work correctly, try the problem-solving approaches described in this chapter. If your app still isn’t working as it should, compare your code with the listings shown at the end of this chapter.

Code and Compiler Warnings

Your code should compile without any warnings. If you do receive warnings, it’s recommended that you treat them as very likely to be errors. Because Objective-C is a very flexible language, sometimes the most you get from the compiler is a warning.

Check the Storyboard File

As a developer, if things don’t work correctly, your natural instinct is probably to check your source code for bugs. But when you use Cocoa Touch, another dimension is added. Much of your app’s configuration may be “encoded” in the storyboard. For example, if you haven’t made the correct connections, your app won’t behave as you expect.

Delegate Method Names

A common mistake with delegates is to misspell the delegate method name. Even if you’ve set the delegate object correctly, if the delegate doesn’t use the right name in its method implementation, the correct method won’t be invoked. It’s usually best to copy and paste delegate method declarations, such as textFieldShouldReturn:, from the documentation.

Code Listings

This section provides listings for the interface and implementation files of the HelloWorldViewController class. Note that the listings don’t show comments and other method implementations that are provided by the Xcode template.

The Interface file: HelloWorldViewController.h

#import <UIKit/UIKit.h>
 
@interface HelloWorldViewController : UIViewController <UITextFieldDelegate>
 
@property (copy, nonatomic) NSString *userName;
 
@end

The Implementation File: HelloWorldViewController.m

#import "HelloWorldViewController.h"
 
@interface HelloWorldViewController ()
 
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *label;
 
- (IBAction)changeGreeting:(id)sender;
 
@end
 
@implementation HelloWorldViewController
 
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
 
- (IBAction)changeGreeting:(id)sender {
 
    self.userName = self.textField.text;
 
    NSString *nameString = self.userName;
    if ([nameString length] == 0) {
        nameString = @"World";
    }
    NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
    self.label.text = greeting;
}
 
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
 
    if (theTextField == self.textField) {
        [theTextField resignFirstResponder];
    }
    return YES;
}
 
@end

Back to Jump Right In