2012-02-16 129 views
0

中聲明當我嘗試編譯這個時,我得到這個錯誤。我需要爲界面中的屬性聲明添加什麼?如果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 

回答

1

的textBox需要,因爲你是在您的實現@synthesizing它被聲明爲一個屬性。

您需要:

  1. 添加@property聲明的textBox在你的界面。或者,如果你不打算需要setter/getter方法,你可以從你的實現中刪除@sythesize這一行。

+0

感謝您的解釋。它在刪除@synthesize行後運行。 – pdenlinger 2012-02-16 21:52:41

1

通過在您的實現中編寫@synthesize textBox編譯器自動爲您生成2個方法。

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

被訪問這些需要在類的接口中定義。 Objective-C爲iPhone提供了一個漂亮的快捷方式來聲明這兩種方法,即@property指令。您還可以包含有關如何將變量存儲在此指令中的信息。

@property (nonatomic, retain) IBOutlet UITextField * textBox 

會給你一個文本字段的IBOutlet。這也是上述兩種方法的一個表現。它告訴我們textBox被你的類保留。通過對變量始終使用setter和getter方法,可以避免在稍後釋放對象並引用實例變量,這可能不安全。這是最好的做法。你會從你的類中做

[self.textBox setText:@"aString"]; 
self.textBox.text = @"aString"; 

訪問文本字段(上面的線是相同的)

+1

除了2個訪問器外,如果你沒有自己的聲明,'@ synthesize'也會生成一個實例變量聲明。這意味着,一旦習慣了@屬性和@合成,你通常不會再編寫自己的變量聲明。 – herzbube 2012-02-16 22:04:48