在 IOS 中,我非常喜欢在 View 之间传递数据,这些 View 直接在使用prepareforsegue 向前传递数据和委托(delegate)将数据传递回来之间进行分隔。
我遇到的问题是,我正在构建一个通过 4 个 View 进行排序的应用程序,然后当用户在第四个 View 上按 Enter 键时,我会弹出其余 View 以返回到第一个 View Controller ,这是 View ,但我不知道如何将数据委托(delegate)回第一个 View 。
我认为问题在于在第一个 View Controller 中设置委托(delegate)。我无法像通常使用 segue.destinationviewcontroller 那样设置它,因为该 View Controller 尚不存在。我应该把它设置在其他地方吗?执行此操作的正确方法是什么?
最佳答案
不要使用委托(delegate)来传递数据,请考虑使用 NSNotificationCenter在这种情况下,您的 View Controller 之间进行通信。
在您的第一个 View Controller 中,您将注册以监听通知:
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleFourthViewSubmit:)
name:@"fourthViewSubmit"
object:nil];
}
并创建发送通知时要运行的方法:
- (void)handleFourthViewSubmit:(NSNotification *)notification {
NSDictionary *theData = [notification userInfo]; // theData is the data from your fourth view controller
// pop views and process theData
}
在您的第一个 View Controller 的 dealloc 方法中,请务必取消注册为观察者(以避免潜在的崩溃):
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
然后在第四个 View Controller 中,按下 Enter 按钮时广播通知:
// note: dataDict should be an NSDictionary containing the data you want to send back to your first view controller
[[NSNotificationCenter defaultCenter] postNotificationName:@"fourthViewSubmit"
object:self
userInfo:dataDict];
关于objective-c - 使用委托(delegate)通过多个 View Controller 传回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12545167/