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

标签 ios uiviewcontroller

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

假设我有 4 个 viewController,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

在我的 .m 文件中,我有以下内容:
#import "BViewController"
#import "CViewController"
#import "DViewController"

@implementation AviewController

@synthesize bViewCon, cViewCon, dViewCon;

- (void) viewDidLoad {

[super viewDidLoad];

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

...

}

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

提前感谢所有回复的人。

最佳答案

您是否考虑过使用 NSNotificationCenter ?在通知上设置方法,并在需要它们运行时对它们执行 ping 操作。如果您的其他 View Controller 已实例化且可用,例如隐藏在导航 Controller 堆栈或单独的选项卡中,这将有所帮助。

要回答有关该错误的问题,您需要在头文件中声明要调用的方法。错误表明它找不到该方法的声明。

通知中心示例

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

关于ios - 需要从另一个viewController调用其他viewController中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14130334/

相关文章:

ios - 在 MKMapView 中使用 UILongPressGestureRecognizer 和可拖动的 MKPinAnnotationView

ios - 与 RestKit 操作会合

ios - 设置整页广告

ios - 如何在 modaly swift 4 中呈现 ViewController

ios - 游戏中心身份验证 View 未显示 - iOS

ios - 如何消除 “Leading and Trailing constraints … there is already a center constraint” 警告

iphone - 如何管理在 UIView 中添加的 subview ?

objective-c - 为什么我的 UIImageView 对象没有实时绘制?

objective-c - 子类化 UIViewController,viewDidLoad 反复调用

ios - 嵌入 UIViewController 的子容器的自动布局