2012-08-13 104 views
0

關於如何在類之間進行交互的一個非常基本的問題是:如何通過單擊鏈接到一個類的按鈕來觸發一個動作(本例中爲圖形用戶界面 - 它不包含任何繪圖代碼)在另一個類(我的繪圖類 - 它是以編程方式定義的)?如何在類之間進行交互

謝謝!

編輯:我試圖實施以下建議的解決方案,但我沒有設法觸發其他課程的行動。我有兩個類:主視圖控制器和具有繪圖代碼的類。任何建議將不勝感激。謝謝!

//MainViewController.m 
//This class has a xib and contains the graphic user interface 

- (void)ImageHasChanged 
{   
//do something on the GUI 
} 


//DrawView.m 
//This class has no associated xib and contains the drawing code 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
//I want to call ImageHasChanged from MainViewController.m here 
//How can I do this? 
} 
+0

你能扔了一些代碼嗎?我不是100%確定你的情況是什麼。如果您將相關代碼插入到您的問題中,我們將能夠爲您提供更多幫助。謝謝! – WendiKidd 2012-08-13 23:38:49

+0

我已經添加了一些代碼。謝謝。 – jeddi 2012-09-18 21:19:34

回答

1

國際級的功能是通過導入一個類到另一個,並呼籲進口的訪問方法/實例變量簡單地完成。

對於你的問題按鈕IBAction爲例如:

ClassA.m(這將通過其頭部被導入):

#import "ClassA.h" 
@implementation ClassA 

// This is a class-level function (indicated by the '+'). It can't contain 
// any instance variables of ClassA though! 
+(void)publicDrawingFunction:(NSString *)aVariable { 
    // Your method here... 
} 

// This is a instance-level function (indicated by the '-'). It can contain 
// instance variables of ClassA, but it requires you to create an instance 
// of ClassA in ClassB before you can use the function! 
-(NSString *)privateDrawingFunction:(NSString *)aVariable { 
    // Your method here... 
} 
@end 

ClassB.m(這是您的UI類將調用其他方法):

#import "ClassA.h" // <---- THE IMPORTANT HEADER IMPORT! 

@implementation ClassB 

// The IBAction for handling a button click 
-(IBAction)clickDrawButton:(id)sender { 

    // Calling the class method is simple: 
    [ClassA publicDrawingFunction:@"string to pass to function"]; 

    // Calling the instance method requires a class instance to be created first: 
    ClassA *instanceOfClassA = [[ClassA alloc]init]; 
    NSString *result = [instanceOfClassA privateDrawingFunction:@"stringToPassAlong"]; 

    // If you no longer require the ClassA instance in this scope, release it (if not using ARC)! 
    [instanceOfClassA release]; 

} 
@end 

注意:如果您要去請求ClassB在ClassB中很多,可以考慮在ClassB中創建一個Class類的實例,以便在需要的地方重新使用它。當你完成它時,不要忘記在dealloc中釋放它(或者可能將它設置爲ARC中的nil)!

最後,請考慮閱讀Apple Docs on Objective-C classes(實際上與您試圖實現的相關文檔的所有其他部分)。這有點費時,但從長遠來看投入很大,可以增強您作爲Objective-C程序員的信心!

+4

公共和私人不是描述+和 - 符號的正確術語。 - 功能是實例級功能;他們操作並可以修改每個類的實例。 +功能是類級功能;無論他們做什麼,他們都無法修改該類的實例變量。從技術上講,Obj-C中的所有方法都是公開的。你可以使用一個類來創建僞私有方法,但即使這些方法可以在程序員知道它們的名字時被調用,因爲在技術上Obj-c作爲一種語言不會進行函數調用;它發送消息。 – WendiKidd 2012-08-13 23:44:40

+0

有一種感覺,我得到了那些錯誤!感謝您指出這一點,我編輯了代碼示例以防止傳播錯誤信息。 – andycam 2012-08-13 23:47:09

+0

@Andeh,你可能想要釋放ClassA的*實例*,而不是類本身。 (我猜你知道,但也許OP沒有。) – matsr 2012-08-13 23:47:36

0

//正如你所說MainViewController的一個實例,必須首先創建

MainViewController *instanceOfMainViewController = [[MainViewController alloc]init]; 
[instanceOfMainViewController ImageHasChanged]; 

//感謝您的幫助Andeh!

相關問題