在我的应用程序中,我有三个受关注的视图控制器。第一个包含一个地图和一个用于打开第二个视图控制器的按钮。第二个视图控制器包含一个可搜索的表,然后当用户选择一行时,它会在第三个视图控制器中加载相关数据。这一切都运作良好!
现在的意图是,当用户按下第三个视图控制器中的Show on Map按钮时,它会将数据(在这种情况下为坐标的两个double值)传递给第一个视图控制器,以便第一个视图然后,控制器可以专注于这些坐标。
我已经关注了Apple的文档(BirdSighting教程)以及之前的问题/答案,但我注意到了一个问题。
我真的找不到将第三视图控制器的委托设置为第一个视图控制器的地方。通常我会在第一个VC中输入以下代码,但我不会创建第三个VC的实例 - 在第二个VC中发生:
thirdVC.delegate = self; //set self as the delegate
那我该怎么办?
由于
答案 0 :(得分:1)
您可以通过secondViewController将委托传递给thirdViewController,或者您可以使用用户通知中心,例如:
NSString *const NotificationDataChanged = @"NotificationDataChanged";
NSDictionary *someData = @{};
[[NSNotificationCenter defaultCenter] postNotificationName:NotificationDataChanged object:someData];
并在firstViewController上需要观察它,例如在viewDidLoad中添加以下行:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateUserInfo:)
NotificationDataChanged object:nil];
- (void)updateUserInfo:(NSNotification *)notification
{
NSDictionary *someData = [notification userInfo];
}
别忘了删除dealloc中的观察者:
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
答案 1 :(得分:1)
代表是实现您所需要的众多机制之一。 @onnoweb的建议非常合适,尽管这可能会让代理指针变得混乱。
KVO: 您还可以考虑KVO,将数据放入模型对象,VC3更新模型对象,VC1是这些值的观察者。
NSNotificationCenter: 另一种选择是NSNotificationCenter
在VC3中,用它来发送广播(设置你的字典包含纬度/经度坐标):
[[NSNotificationCenter defaultCenter] postNotificationName:@"ShowOnMap" object:[NSDictionary dictionaryWithObjects:objects forKey:keys]];
VC1中的:
注册接收广播:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onShowOnMap:) name:@"ShowOnMap" object:nil];
并处理广播:
-(void) onShowOnMap:(NSNotification *)notification
{
NSDictionary *values = [notification object];
.
.
.
}
并取消注册你的dealloc
答案 2 :(得分:0)
您可以在AppDelegate中存储指向第一个VC的指针,以便您可以调用
thirdVC.delegate =[(AppDelegate*)[NSApplication sharedApplication].delegate firstVC];