クラス間機能は、一方のクラスをもう一方のクラスにインポートし、インポート時にアクセス可能なメソッド/インスタンス変数を呼び出すだけで実行されます。
質問のボタン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でリリースすることを忘れないでください(またはnil
ARCで設定することもできます)。
最後に、Objective-Cクラスに関するApple Docs(および実際に達成しようとしていることに関連するドキュメントの他のすべてのセクション)を読むことを検討してください。少し時間がかかりますが、Objective-Cプログラマーとしての自信を築くために、長期的には非常によく投資されています。