Documentation Archive Developer
Search

排除故障和检查代码

如果应用程序未能正确工作,请尝试本章描述的解决问题方法。如果应用程序仍然不能正确工作,请将您的代码与本章末尾给出的清单进行比较。

代码和编译器警告

代码编译时应该不会有任何警告。如果真的收到警告,就很有可能是代码出错了。因为 Objective-C 是一种非常灵活的程序设计语言,有时候编译器给出的也仅仅是一些警告而已。

检查串联图文件

如果程序未能正确工作,开发者会很自然地去检查源代码来找出错误。但使用 Cocoa Touch,又增添了另一个层面。应用程序的大部分配置可能是“编码”在串联图中。例如,如果连接不正确,应用程序的行为就会与您的期望不符。

委托方法的名称

与委托有关的一个常见错误是拼错委托方法的名称。即使已经正确设定了委托对象,但是如果委托未在其方法实现中使用正确的名称,则不会调用正确的方法。通常最好的做法是从文稿中拷贝和粘贴委托方法声明(例如 textFieldShouldReturn:)。

代码清单

这一部分提供 HelloWorldViewController 类的接口和实现文件的代码清单。请注意,该清单并未列出 Xcode 模板提供的注释和其他方法的实现。

接口文件:HelloWorldViewController.h

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

实现文件: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

返回“马上开始”