如何将数据传递给另一个视图控制器?

时间:2018-02-04 03:24:00

标签: ios objective-c uitableview

我有一个具有以下功能的视图控制器A: -

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
         [tableView deselectRowAtIndexPath:indexPath animated:YES];

        Events_TableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];

        EventDetail_ViewController *eventDetailController = [[EventDetail_ViewController alloc] initWithNibName:@"EventDetail_ViewController" bundle:nil];
        [[self navigationController] pushViewController:eventDetailController animated:YES];

        eventDetailController.title = cell.nameLabel.text;

        eventDetailController.Description.text = cell.lblDescription.text;
        eventDetailController.Date.text = cell.lblDate.text;
            eventDetailController.Location.text = cell.lblAddress.text;

}

我能够在View控制器B中获取eventDetailController.title值(示例屏幕如下),但是我没有获得描述,日期和位置值。如果我把NSLog放在上面的代码中,我将能够获得该值。

enter image description here

请帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

如果要将信息从一个对象传递到另一个不相关的对象,一种方法是使用notifications。您通常希望对象要求接收如下通知:

[[NSNotificationCenter defaultCenter] addObserver:self  // view controller B
                                         selector:@selector(handleNotification: )
                                             name:@"Some Notification Name" // This should be something meaningful in your app
                                           object:soemObject // Either a particular object or nil if you want to receive the notification from any object
];

然后在您的视图控制器A中,您可以通过以下方式发送您想要的任何信息:

[[NSNotificationCenter defaultCenter] postNotificationName:@"Some Notification Name" // Same as above
                                                    object:self
                                                  userInfo:userInfo // An NSDictionary with whatever needs to be transmitted to the other controller in it
];

然后在你的视图控制器B中,你想要收到你用上面发送到-addObserver:::的选择器编写方法的信息,如下所示:

- (void)handleNotification:(NSNotification*)notification
{
    NSDictionary* userInfo = [notification userInfo];
    // userInfo contains the data that was sent from view controller A
    // do something here with that information. 
}

这是一种在任何2个对象之间进行通信的方式,而不是直接coupling它们在一起。

相关问题