2011-04-29 31 views
0
#import <Foundation/Foundation.h> 

@interface MyClass : NSObject { 
@private 
    IBOutlet NSTextField *tf; 
} 
- (void)setStr; 

@end 

=========================================== 

#import "MyClass.h" 

@implementation MyClass 

- (id)init 
{ 
    self = [super init]; 
    if (self) { 
     // Initialization code here. 
    } 

    return self; 
} 

- (void)dealloc 
{ 
    [super dealloc]; 
} 

- (void)setStr 
{ 
    [tf setStringValue:@"aaaaaaaaa"]; 
} 

@end 

調用一個方法從我AppDelegate類無法從我的課獲得形式的訪問

- (IBAction)test1:(id)sender 
{ 
    MyClass *m = [[MyClass alloc] init]; 
    [m setStr]; 
} 

我的.xib文件中創建的MyClass的對象。我將textfield的出口與表單上的文本字段相關聯。 按下按鈕時沒有動作。 我錯了?

+0

當你說XIB文件,我相信你的意思是一個看法。 – user210504 2011-04-29 12:10:01

+0

你爲同一個類創建第二個對象。一個是來自appdelegate,另一個是在類和你問textfeild文本,那麼你不得不提到,如果它是cocoatouch UITextfeild .. – ajay 2011-04-29 12:22:26

+0

@ user210504,我不認爲這就是他的意思。我認爲他在他的XIB文件中有一個MyClass的實例,因此在運行時在他的NIB中。 – Dov 2011-04-29 12:30:52

回答

0

您需要在AppDelegate中爲MyClass創建一個插座並將其連接起來,然後在test1中使用該插座而不是創建新實例。這guide from Apple應該可以幫到你。

另一種可能性是將test1動作放入MyClass,並通過按鈕按鈕直接調用它,或使setStr爲IBAction。這些都是可能的,因爲在XIB中有一個MyClass實例。

+0

「您需要爲AppDelegate中的MyClass創建一個插座並將其連接起來,然後在test1中使用該插座而不是創建新實例。」 ..請告訴我如何做到這一點? – Novikoff 2011-04-29 12:41:49

+0

與創建'IBOutlet NSTextField * tf;'相同的方法。坐在你的XIB中的MyClass實例和坐在窗口內的對象是一樣的。我用一個可能幫助你的鏈接更新了我的答案。 – Dov 2011-04-29 12:43:57