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

sye*_*dfa 1 uiviewcontroller ios

我有一个具有多个viewControllers的应用程序,其中一些viewControllers包含运行各种任务的方法.我需要做的是当初始viewController加载时,是在其他viewControllers中调用这些方法使它们在后台运行,但是,我在执行此操作时遇到了一些困难.

假设我有4个viewControllers,A,B,C和D,其中A是最初的viewController,在每个viewController中,我分别有aMethod,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
Run Code Online (Sandbox Code Playgroud)

在我的.m文件中,我有以下内容:

#import "BViewController"
#import "CViewController"
#import "DViewController"

@implementation AviewController

@synthesize bViewCon, cViewCon, dViewCon;

- (void) viewDidLoad {

[super viewDidLoad];

bViewCon = [[BViewController alloc] init];
[bViewCon bMethod];

...

}
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误消息,"没有可见的@interface为'BViewController'声明选择器'bMethod'".我需要从这个类(即AViewController)以相同的方式从其他viewControllers调用其他方法.

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

Bil*_*ess 5

你考虑过用过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
Run Code Online (Sandbox Code Playgroud)