需要从另一个viewController调用其他viewController中的方法

我有一个应用程序有多个viewControllers,其中一些viewControllers包含运行各种任务的方法。 我需要做的是,当初始viewController加载,是调用其他viewControllers这些方法,使他们在后台运行,但是,我有一些困难这样做。

假设我有4个viewControllers,A,B,C和D,其中A是最初的viewController,在每个viewController中,我分别有一个方法,bMethod,cMethod和dMethod。 这是相关的代码:

里面我打开viewController(AviewController):

在.h文件中:

#import "BViewController" #import "CViewController" #import "DViewController" @interface AViewController:UIViewController { BViewController *bViewCon; CViewController *cViewCon; DViewController *dViewCon; } @property (nonatomic, retain) BViewController *bViewCon; @property (nonatomic, retain) CViewController *cViewCon; @property (nonatomic, retain) DViewController *dViewCon; @end 

在我的.m文件中,我有以下几点:

 #import "BViewController" #import "CViewController" #import "DViewController" @implementation AviewController @synthesize bViewCon, cViewCon, dViewCon; - (void) viewDidLoad { [super viewDidLoad]; bViewCon = [[BViewController alloc] init]; [bViewCon bMethod]; ... } 

但是,我收到错误消息,“没有可见的@接口为'BViewController'声明select器'bMethod'”。 我需要从这个类(即AViewController)以相同的方式从其他viewController调用其他方法。

在此先感谢所有回复的人。

要解决您收到的错误,请确保所有的方法都在每个控制器的头文件(.h)中声明(否则,编译器将无法看到它们)。

由于所有这些控制器都是AViewControllerAViewController (它们是由AViewController创build的,并保存为ivars),所以我不会在这里使用NSNotificationCenter (除非在某些事件发生时还需要通知其他对象,不属于AViewController )。

相反,我只是直接调用方法,就像你试图做的那样。

在另一个说明中,如果这些方法正在执行正在执行的任务(在后台运行任务),最好将方法调用移动到AViewControllerinit:方法。 (和iOS 5一样,视图可以被卸载,因此viewDidLoad:可以被多次调用,比如内存警告和视图被屏蔽)。 我可能会去做这样的事情:

 - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle { self = [super initWithNibName:nibName bundle:bundle]; // your correct stuff here if (self) { bViewCon = [[BViewController alloc] init]; [bViewCon bMethod]; // ... and so on for the other controllers } return self; } 

编辑

虽然,正如在评论中所提到的, UIViewController在内存方面并不是很便宜,但实际上最好是将这些代码重构成一个单一的控制器( NSObject一个子类而不是UIViewController ,它便宜)充当将要在后台运行的任务的pipe理者。 我想这也许会帮助你后来的事情,因为这将有助于划分每个控制器的任务和目的(在这种情况下, UIViewController应该主要负责pipe理视图(在某些情况下是/视图层次结构)和相关的任务…如果正在进行的任务发生在与所述视图相关联的事物的范围之外,则可能是UIViewController不应该处理它们的迹象…

你有没有考虑过使用NSNotificationCenter ? 在通知上设置方法,只需要在需要时运行即可。 如果你的其他视图控制器是实例化和可用的,就像埋在导航控制器堆栈或单独的选项卡中一样。

要回答你关于那个错误的问题,你需要在头文件中声明你想调用的方法。 错误是说它找不到该方法的声明。

通知中心的例子

 // listen for notifications - add to view controller doing the actions [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mySpecialMethod) name:@"SomeNotificationName" object:nil]; // when you want your other view controller to do something, post a notification [[NSNotificationCenter defaultCenter] postNotificationName:@"SomeNotificationName" object:nil]; // you don't want this notification hanging around, so add this when you are done or in dealloc/viewDidUnload [[NSNotificationCenter defaultCenter] removeObserver:self]; // this removes all notifications for this view // if you want to remove just the one you created, you can remove it by name as well