属性实现必须在接口中声明

时间:2012-02-16 21:43:13

标签: ios

当我尝试编译时,我收到此错误。我需要为界面中的属性声明添加什么?如果textBox是一个实例变量,为什么需要将它声明为属性?

ViewController.h

#import <UIKit/UIKit.h>

@interface TNRViewController : UIViewController {

    IBOutlet UITextField *textBox;
    IBOutlet UILabel *label;
}
- (IBAction)button:(id)sender;

@end

ViewController.m

#import "TNRViewController.h"

@implementation TNRViewController
@synthesize textBox;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)dealloc {
    [textBox release];
    [label release];
    [super dealloc];
}
- (IBAction)button:(id)sender {
    NSString *Name = textBox.text;
    NSString *Output = Nil;
    Output = [[NSString alloc] initWithFormat:@"%@ says: Hello World!", Name];
    label.text = Output;
    [Output release];
}

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

3 个答案:

答案 0 :(得分:1)

需要将textBox声明为属性,因为您在实现中对它进行了@synthesizing。

您需要:

  1. 在界面中添加textBox的@property声明。

  2. 或者,如果您不打算需要setter / getter方法,可以从实现中删除@sythesize行。

答案 1 :(得分:1)

通过在实现中编写@synthesize textBox,编译器会自动为您生成两种方法。

-(UITextField*)textBox
-(void)setTextBox:(UITextField *)textBox

要访问这些,需要在类的接口中定义。 iPhone的Objective-C有一个很好的捷径来声明这两个方法@property指令。您还可以包含有关变量应如何存储在此指令中的信息。

@property (nonatomic, retain) IBOutlet UITextField * textBox

会为您提供文本字段的IBOutlet。它也是上述两种方法的立足点。它告诉我们你的类保留了textBox。通过始终对变量使用setter和getter方法,可以避免在以后释放对象并引用实例变量时,它可能不安全。这是最好的做法。您可以通过

访问班级中的文本字段
[self.textBox setText:@"aString"];
self.textBox.text = @"aString";

(以上几行相同)

答案 2 :(得分:0)

我添加广告连播时发生了此错误。我最终删除了更新的Pod文件,并修复了该错误。

相关问题