[英]How to interact between classes
一个关于如何在类之间进行交互的非常基本的问题:如何在另一个类(我绘图类-以编程方式定义的)?
谢谢!
编辑:我试图实现以下建议的解决方案,但是我没有设法触发其他类的操作。 我有两个类:主视图控制器和一个带有绘图代码的类。 任何建议将不胜感激。 谢谢!
//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?
}
类间功能的实现很简单,只需将一个类导入另一个,然后在导入中调用可访问的方法/实例变量即可。
对于您问题中的按钮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中释放它(或者在ARC中将其设置为nil
)!
最后,请考虑阅读有关Objective-C类的Apple文档 (以及文档中与您要达到的目标有关的所有其他部分)。 这有点耗时,但是从长远来看,要投入很多钱来树立您作为Objective-C程序员的信心!
//正如您所说的,必须先创建MainViewController的实例
MainViewController *instanceOfMainViewController = [[MainViewController alloc]init];
[instanceOfMainViewController ImageHasChanged];
//感谢您的帮助Andeh!
实际上,您可以使用@protocol(Delegate)在两个类之间交互消息,这是标准方法,或者可以参考此文档http://developer.apple.com/library/ios/#documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources。 html了解更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.