I am using notifications to pass data from a detail view controller to the rootviewcontroller in my app. The methods work fine until there is a memory warning.
The notification is handled twice after any memory warnings.
I pass data back to the rootviewcontroller when the user selects a row in the DetailViewController. The didSelectRowAtIndexPath method is called just once but the notification observer is called twice!
Should I be removing the notification in didReceiveMemoryWarning? Or is there some other problem with the code?
Posting the relevant code
RootViewController’s viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rowSelected:) name:@"SelectionNotification" object:nil];
DetailViewController’s 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];
}
Thanks for any help.
I’m quite new to iPhone development, but what I noticed so far is that after a memory warning, the default implementation of the didReceiveMemoryWarning method is to unload the view if it’s not visible.
I think in your case, the root view controller is not visible, and therefor unloaded. Once you pop back to the root view controller, the viewDidLoad method is called again, and so the view controller instance (which itself is not unloaded, just the view is) registers itself again to the notification center.
The solution would be to register in the notification center at initialization time, either being in the default init method, or the
initWithNibName:bundle:method, or in theinitWithCoder:method.