2014-01-21 118 views
0

我有在這裏不同類從訪問的NSTextField值的問題是代碼:可可的NSTextField

AppDelegate.h

#import <Cocoa/Cocoa.h> 

@interface AppDelegate : NSObject <NSApplicationDelegate> 

@property (assign) IBOutlet NSWindow *window; 
@property (weak) IBOutlet NSTextField *numberOfPhrases; 

@end 

AppDelegate.m

#import "AppDelegate.h" 

@implementation AppDelegate 
@synthesize numberOfPhrases; 


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    NSLog(@"%@",[numberOfPhrases stringValue]); 
} 

TestClass.h

@interface TestClass : NSObject 

- (IBAction)doSomething:(id)sender; 

@end 

TestClass.m

@implementation TestClass 

- (IBAction)doSomething:(id)sender { 


    NSLog(@"%@",[numberOfPhrases stringValue]); ????????? 


} 

回答

0

你唯一缺少的是除了你TestClass.m文件:

#import "TestClass.h" 
#import "AppDelegate.h" 

@implementation TestClass 

- (IBAction)doSomething:(id)sender { 

    AppDelegate *theInstance = [[AppDelegate alloc] init]; 
    [theInstance numberOfPhrases]; 

} 

@end 

您需要包括AppDelegate.h類的頭在TestClass.m,那麼你只需通過[[AppDelegate alloc] init];調用實例您需要將您的NSTextField鏈接到已發送操作的Interface Builder do:Something -> TestClass參考插座numberOfPhrases -> AppDelegate

輸出

2014-01-21 23:32:56.499 test[6236:303] Wonders Never Cease 
+0

對不起,但我們仍然錯過了點 – crazyjuice

+0

我想從AppDelegate中初始化的textfiled中獲取值。我必須在TestClass中實例化AppDelegate? – crazyjuice

+0

@crazyjuice,錯過這一點會讓代碼不運行 - 如果你有錯誤,在繼續之前需要糾正。 –

1

你顯然不能在其他類沒有鏈接到它訪問文本字段值。

要訪問文本字段的值,您需要在此類中再添加一個IBOutlet,或者在AppDelegate中添加一個IBOutlet,以便您可以訪問其屬性。

TestClass.h

@interface TestClass : NSObject 
{ 
    IBOutlet NSTextField *numberOfPhrases; // connect it to the new referencing outlet of text field by dragging a NSObject object in your xib and setting its class to "TestClass" 
} 

- (IBAction)doSomething:(id)sender; 

@end 

或另一種選擇是讓AppDelegate中的識別TestClass一個IBOutlet中(因爲如果你只是創建的AppDelegate而不是其IBOutlet中的一個新的實例,然後文本字段的不同實例將創建成功,您將無法訪問您的文本字段的值)

TestClass.h

@interface TestClass : NSObject 
{ 
    IBOutlet AppDelegate *appDel; // connect in the xib 
} 

- (IBAction)doSomething:(id)sender; 

@end 

TestClass.m

@implementation TestClass : NSObject 

- (IBAction)doSomething:(id)sender 
{ 
    [[appDel numberOfPhrases]stringValue]; //get the string value in text field 
} 

@end 
+0

thx回覆並遺憾丟失的代碼部分(這應該用僞代碼寫) – crazyjuice

相關問題