如何在类之间进行交互

时间:2012-08-13 23:19:09

标签: iphone ios

关于如何在类之间进行交互的一个非常基本的问题:如何通过单击链接到一个类的按钮(在我的情况下是图形用户界面 - 不包含任何绘图代码)触发一个调用的动作class(我的绘图类 - 以编程方式定义)?

谢谢!

编辑:我已尝试实施下面建议的解决方案,但我没有设法从其他类触发操作。我有两个类:主视图控制器和带有绘图代码的类。任何建议都将受到高度赞赏。谢谢!

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

3 个答案:

答案 0 :(得分: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中释放它(或者可能在ARC中将它设置为nil!)

最后,请考虑阅读Apple Docs on Objective-C classes(以及文档中与您尝试实现的内容相关的所有其他部分)。这有点耗时,但是从长远来看,我非常注重建立您作为Objective-C程序员的信心!

答案 1 :(得分:0)

//正如你所说,必须首先创建一个MainViewController实例

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

//感谢你的帮助Andeh!

答案 2 :(得分:0)

实际上你可以使用@protocol(Delegate)来交换两个类之间的消息这是标准的方法或者参考这个文档 http://developer.apple.com/library/ios/#documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html了解更多信息