您可以使用NSNotificationCenter
如下所示:
首先在您的应用程序委托中发布通知:
NSDictionary *_dictionary=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%d",newIndex],nil] forKeys:[NSArray arrayWithObjects:SELECTED_INDEX,nil]];
[[NSNotificationCenter defaultCenter] postNotificationName:SELECT_INDEX_NOTIFICATION object:nil userInfo:_dictionary];
然后注册你想要观察这个通知的 ViewController
/***** To register and unregister for notification on recieving messages *****/
- (void)registerForNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(yourCustomMethod:)
name:SELECT_INDEX_NOTIFICATION object:nil];
}
/*** Your custom method called on notification ***/
-(void)yourCustomMethod:(NSNotification*)_notification
{
[[self navigationController] popToRootViewControllerAnimated:YES];
NSString *selectedIndex=[[_notification userInfo] objectForKey:SELECTED_INDEX];
NSLog(@"selectedIndex : %@",selectedIndex);
}
在 ViewDidLoad 中调用此方法为:
- (void)viewDidLoad
{
[self registerForNotifications];
}
然后在 UnLoad 上通过调用此方法删除此观察者:
-(void)unregisterForNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:SELECT_INDEX_NOTIFICATION object:nil];
}
-(void)viewDidUnload
{
[self unregisterForNotifications];
}
希望它可以帮助你。