iPhone应用程序中的异常错误

时间:2009-07-11 08:57:17

标签: iphone objective-c

在我的hello world应用程序中,我有一个按钮和一个文本字段设置。你在文本字段中输入你的名字,然后按下按钮,然后你应该看到“你好,[名字]!”。但我得到的只是“你好,世界!” (即使我输入名称时,文本框中没有字符串的默认值)。根据要求,这是文件:

//
//  MyViewController.m
//  HelloWorld
//
//  Created by RCIX on 7/10/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MyViewController.h"

@implementation MyViewController

@synthesize textField;
@synthesize label;
@synthesize string;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [textField release];
    [label release];
    [string release];
    [super dealloc];
}
- (IBAction)changeGreeting:(id)sender {
    self.string = textField.text;
    NSString *nameString = self.string;
    if ([nameString length] == 0) {
        nameString = @"World";
    }
    NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
    label.text = greeting;
    [greeting release];
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
        [theTextField resignFirstResponder];
    return YES;
}

@end

3 个答案:

答案 0 :(得分:1)

在Interface Builder中仔细检查您的连接。如果textField未正确连接,则您的方法将无法读取该字段的text属性,这可能会导致其长度为0.

答案 1 :(得分:1)

没有必要使nameString = string,只需直接处理[self string]!

这是一个工作示例:

string = textField.text;
if ([string length] == 0) {
    string = @"World";
}

NSString *greeting = [NSString stringWithFormat:@"Hello, %@!", string];
[label setStringValue:greeting];

你会看到我将initWithFormat更改为stringWithFormat。如果你使用stringWithFormat,NSString对象是自动释放的,所以我们不必担心释放它。

最后一件事......我并不认为需要让“string”成为一个实例变量,因为它只是暂时使用...它可能会更好地去

NSString *string = textField.text; 

并没有在@interface中声明它......只是一个想法。

答案 2 :(得分:0)

文本字段是否在Interface Builder中正确连接?