您可以使用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];
然後註冊您需要的視圖控制器觀察此通知爲
/***** 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];
}
,然後卸載通過調用此方法刪除此觀察:
-(void)unregisterForNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:SELECT_INDEX_NOTIFICATION object:nil];
}
-(void)viewDidUnload
{
[self unregisterForNotifications];
}
希望它可以幫助你。
您好,其中i必須把這個代碼:[[NSNotificationCenter defaultCenter] 的addObserver:自 選擇器:@selector(:)的getData notificationName:@ 「數據」 對象:yourdata]; – Marv 2013-05-09 09:13:37
你想檢查通知數據,你可以把它叫做viewDidLoad – Buntylm 2013-05-09 09:21:39
我們如何才能將你的數據作爲viewController中的對象? – 2015-02-25 07:11:43