2

在 IOS 中,我很乐意在视图之间传递数据,这些视图直接在使用 prepareforsegue 向前传递数据和委托将其传递回来之间进行分隔。

我遇到的问题是我正在构建一个通过 4 个视图分隔的应用程序,然后当用户在第四个视图上按 Enter 时,我弹出其余视图以返回到第一个视图控制器和它的视图,但是我不知道如何将数据委托给第一个。

我相信问题在于在第一个视图控制器中设置委托。我无法像通常使用 segue.destinationviewcontroller 那样设置它,因为该视图控制器尚不存在。我应该把它设置在别的地方吗?这样做的正确方法是什么?

4

1 回答 1

4

在这种情况下,考虑使用NSNotificationCenter在视图控制器之间进行通信,而不是使用委托来传递数据。

在您的第一个视图控制器中,您将注册以侦听通知:

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

}

在您的第一个视图控制器的 dealloc 方法中,请务必取消注册为观察者(以避免潜在的崩溃):

-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

然后在您的第四个视图控制器中,在按下回车按钮时广播通知:

// 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];
于 2012-09-22T16:08:04.533 回答