2010-06-18 40 views
4

我想弄清楚如何从另一个类调用函数。我使用的是RootViewController的设置自己的看法作为一个可以说AnotherViewController从另一个类调用函数 - Obj C

所以在我AnotherViewController即时将添加在.h文件

@class RootViewController 

而在.m文件即时将导入查看

#import "RootViewController.h" 

我有一个调用的函数:

-(void)toggleView { 
//do something } 

然后在我的AnotherViewController我分配了一个按钮:

-(void)buttonAction { 
//} 

在我想能够调用该函数toggleView在我的RootViewController的的buttonAction。

有人可以澄清我如何做到这一点。

我尝试添加这是我buttonAction:

RootViewController * returnRootObject = [[RootViewController alloc] init]; 
    [returnRootObject toggleView]; 

但我不认为这是正确的。

谢谢先进。

回答

1

你会想在你的AnotherViewController中创建一个委托变量,当你从RootViewController初始化它时,将RootViewController的实例设置为AnotherViewController的委托。

为此,请向AnotherViewController添加一个实例变量:“id delegate;”。然后,添加了两种方法来AnotherViewController:

- (id)delegate { 
    return delegate; 
} 

- (void)setDelegate:(id)newDelegate { 
    delegate = newDelegate; 
} 

最后,在RootViewController的,无论AnotherViewController被初始化,做

[anotherViewControllerInstance setDelegate:self]; 

然后,当您要执行toggleView,做

[delegate toggleView]; 

或者,你可以让你的RootViewController成为单例,但是委托方法当然是更好的做法。我还想指出,我刚才告诉你的方法是基于Objective-C 1.0的。 Objective-C 2.0有一些新的属性,但是当我学习Obj-C时,这让我困惑不已。在查看属性之前,我会获得1.0的优先级(这样你就会明白他们先做什么,他们基本上只是自动让getter和setter)。

1

我试用了NSNotificationCentre - 像魅力一样工作 - 感谢您的回复。我无法得到它的运行,但NS已经得到它的轰鸣。

[[NSNotificationCenter defaultCenter] postNotificationName:@"switchView" object: nil]; 
+0

这不是最有效的方法,完全通过NSNotificationCenter处理类间通信确实不是很好的做法。我真的建议你看一下委托方法或者至少一个单例。 – AriX 2010-06-21 01:27:06