gpt4 book ai didi

ios - 两个不同的 View Controller 如何相互通信

转载 作者:可可西里 更新时间:2023-11-01 06:18:06 25 4
gpt4 key购买 nike

我有一个带有选项卡栏和 3 个不同 View Controller 的应用程序。其中之一管理我通过 Interface Builder( Storyboard)设计的 UItableView,我在 Inspector -> inspector identity -> 中设置它的 View Controller 类,然后在那里设置类字段,因此,当这个 View Controller 获取时我无法控制实例化,因为它是在用户单击选项卡栏时通过 Storyboard完成的。请注意,我是 Objective C 和 iOS 编程的新手。

我面临的问题,我也在使用远程通知。因此,当我在 AppDelgate 类的“didReceiveRemoteNotification”中收到远程通知消息时。我需要更新 UI 界面(在 ViewController 之上),但问题是我没有从我的 AppDelgate 类(或者我有吗?)对此 ViewController 的引用(指针)。这个 ViewController 由 Storyboard或编程方式实例化的问题,否则我可以保留对它的引用。

我读了一些书,我知道我可以通过 NSNotification 进行这种交流,但我认为这对于可能出现的问题来说太过分了,因为我是新手而且我对 iOS 没有完全理解发展。

谢谢,

最佳答案

NSNotifications 易于使用,可能是正确的解决方案。

在需要发送消息的app delegate中,只要放:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:someObjectYouWantToPassCouldBeAppDelegateOrRemoteNotificationObjectOrAnything];

在接收消息的 View Controller 中,放置:

-(void)viewDidLoad
{
[super viewDidLoad];

//you can add as many of these as you like to handle different notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
}

-(void)viewDidUnload
{
//make sure you remove every observer you've added here
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];

[super viewDidUnload];
}

-(void)dealloc
{
//clean up in case viewDidUnload wasn't called (it sometimes isn't)
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}

//use a different handler method for each notification
//the method name should match the selector in your observe call in viewDidLoad
-(void)handleNotification:(NSNotification *)notification
{
WhateverClassOfObjectYouWerePassing *object = notification.object;

//now you have a reference to the object that was passed from your app delegate
}

对于您想调用的不同方法,只需一个新的通知名称和一个新的处理程序方法。

关于ios - 两个不同的 View Controller 如何相互通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9127696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com