views:

588

answers:

2

Hi

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.

+1  A: 

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 the initWithCoder: method.

drvdijk
just assume that your View will be loaded and unloaded multiple times and code accordingly.
David Maymudes
+2  A: 

As you are hinting, if you subscribe to a notification twice, you will receive it twice.

Most likely you are re-instantiating a deallocated object and re-subscribing to the notification.

Set a breakpoint where you subscribe to notifications and you will most likely hit it twice.

You can override the accessor and unsubscribe from notifications there. Or you can do it with KVO.

Corey Floyd