2014-01-15 42 views
2

嗨,我最近完成了一本關於目標c的基礎知識的教程書。現在我正在「嘗試」製作一個簡單的應用程序。現在我似乎有最簡單的問題,我似乎無法解決,也許你可以告訴我我做錯了什麼。如何正確查看NSTextField的數據?

AppDelegate.h

#import <Cocoa/Cocoa.h> 

    @interface AppDelegate : NSObject <NSApplicationDelegate> 

    @property (assign) IBOutlet NSWindow *window; 
    - (IBAction)saveData:(id)sender; 
    //Below is a simple IBOutlet which I try to retrieve data from when the IBAction saveData occurs 
    @property (weak) IBOutlet NSTextField *foodName; 


    @end 

AppDelegate.m

#import "AppDelegate.h" 

    @implementation AppDelegate 

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
    { 
     // Insert code here to initialize your application 
    } 
    //Here is the saveData IBAction which should print out the value of the NSTextField if the user entered a value (if not returns null) 
    - (IBAction)saveData:(id)sender { 
     NSLog(@"%@", foodName.stringValue); 
     NSLog(@"Saved"); 
    } 
    @end 

我好像是構建就會失敗,並給我在這條線在AppDelegate.m錯誤消息的問題:

NSLog(@"%@", foodName.stringValue); 

錯誤消息是:使用未聲明的標識符'foodName';你的意思是'_foodName'?

有人能解釋一下怎麼回事,我該如何解決這個問題?

回答

0

地址 getter方法,使用self.

NSLog(@"%@", self.foodName.stringValue); 

而且,一個小點:組中的所有@property聲明一起在@interface聲明的開始,但之後的任何實例變量聲明:

@interface MyClass : NSObject { 
    NSString *_str1; 
    int _i1; 
} 
@property (weak) IBOutlet NSString *something; 
@property (strong, readonly) NSNumber *somethingElse; 
- (int)aMethod:(NSString *)string; 
- (void)anotherMethod; 
@end 
+0

感謝您的快速回復,好奇爲什麼它需要自我? – Mutch95

+0

@ Mutch95您正在使用自動生成的實例變量,默認情況下,實例變量是_foodName(如您發佈的編譯器錯誤所示)。要訪問一個方法(這就是getter和setter),你總是需要一個對象實例(本例中爲self),形式爲self.foodName或者[self foodName]或者[self setFoodName: ]'。 – trojanfoe