0

ここでのクラス間の対話方法に関する非常に基本的な質問:別のクラス(私の場合は描画コードを含まない)にリンクされたボタンをクリックして呼び出されるアクションをトリガーするにはどうすればよいですか?描画クラス-プログラムで定義されます)?

ありがとう!

編集済み:以下に提案するソリューションを実装しようとしましたが、他のクラスからアクションをトリガーすることができませんでした。メインビューコントローラと描画コードを持つクラスの2つのクラスがあります。アドバイスをいただければ幸いです。ありがとう!

//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?
}
4

3 に答える 3

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でClassAを大量に必要とする場合は、ClassBでクラス全体のインスタンスを作成して、必要な場所で再利用することを検討してください。使い終わったら、deallocでリリースすることを忘れないでください(またはnilARCで設定することもできます)。

最後に、Objective-Cクラスに関するApple Docs(および実際に達成しようとしていることに関連するドキュメントの他のすべてのセクション)を読むことを検討してください。少し時間がかかりますが、Objective-Cプログラマーとしての自信を築くために、長期的には非常によく投資されています。

于 2012-08-13T23:39:08.083 に答える
0

//おっしゃるように、MainViewControllerのインスタンスを最初に作成する必要があります

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

//助けてくれてありがとうAndeh!

于 2012-09-19T05:21:23.577 に答える
0

実際には、@ protocol(Delegate)を使用して、2つのクラス間でメッセージをやり取りできます。これは標準的な方法です。または、このドキュメント http://developer.apple.com/library/ios/#documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSourcesを参照してください。詳細についてはhtml

于 2012-09-19T09:13:36.923 に答える