[英]iPhone - notification posted twice after memory warning
我正在使用通知將數據從詳細信息視圖控制器傳遞到我的應用程序中的rootviewcontroller。 該方法可以正常工作,直到出現內存警告。
出現任何內存警告后,通知將被處理兩次。
當用戶在DetailViewController中選擇一行時,我會將數據傳遞回rootviewcontroller。 didSelectRowAtIndexPath方法僅被調用一次,但是通知觀察者被調用兩次!
我應該在didReceiveMemoryWarning中刪除通知嗎? 還是代碼還有其他問題?
發布相關代碼
RootViewController的viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rowSelected:) name:@"SelectionNotification" object:nil];
DetailViewController的didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
[dictionary setObject:selectedRow forKey:@"row"];
[[NSNotificationCenter defaultCenter] postNotificationName:kSelectionNotificationName object:self userInfo:dictionary];
[[self navigationController] popToRootViewControllerAnimated:YES];
}
謝謝你的幫助。
我對iPhone的開發還很陌生,但是到目前為止,我注意到的是在發生內存警告后,didReceiveMemoryWarning方法的默認實現是在視圖不可見時卸載視圖。
我認為在您的情況下,根視圖控制器不可見,因此已卸載。 彈出到根視圖控制器后,再次調用viewDidLoad方法,因此視圖控制器實例(其本身並未卸載,只是視圖已被加載)再次將其自身注冊到通知中心。
解決方案是在初始化時在通知中心中注冊,可以使用默認的init方法或initWithNibName:bundle:
方法或initWithCoder:
方法。
如您所暗示的,如果您兩次訂閱通知,您將收到兩次。
您很可能正在重新實例化一個釋放對象並重新訂閱該通知。
在您訂閱通知的地方設置一個斷點,您很可能會擊中兩次。
您可以覆蓋訪問器,並在那里取消訂閱通知。 或者,您也可以使用KVO。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.