【问题标题】:iPhone - notification posted twice after memory warningiPhone - 在内存警告后发布两次通知
【发布时间】:2009-07-01 07:26:55
【问题描述】:

我正在使用通知将数据从详细视图控制器传递到我的应用程序中的根视图控制器。在出现内存警告之前,这些方法都可以正常工作。

在任何内存警告后处理两次通知。

当用户在 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 notifications


    【解决方案1】:

    我对 iPhone 开发还很陌生,但到目前为止我注意到的是,在内存警告之后,didReceiveMemoryWarning 方法的默认实现是在视图不可见时将其卸载。

    我认为在您的情况下,根视图控制器不可见,因此已卸载。一旦你弹回根视图控制器,viewDidLoad 方法就会再次被调用,因此视图控制器实例(它本身并没有被卸载,只是视图被卸载)再次将自己注册到通知中心。

    解决方案是在初始化时在通知中心注册,或者在默认的init方法中,或者在initWithNibName:bundle:方法中,或者在initWithCoder:方法中。

    【讨论】:

    • 假设您的视图将被加载和卸载多次并相应地编码。
    【解决方案2】:

    正如您所暗示的,如果您订阅了两次通知,您将收到两次。

    您很可能正在重新实例化已释放的对象并重新订阅通知。

    在订阅通知的位置设置断点,您很可能会点击两次。

    您可以覆盖访问器并在此处取消订阅通知。或者你可以用 KVO 来做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-04
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2010-12-22
      • 2019-03-24
      相关资源
      最近更新 更多