繁体   English   中英

iPhone-内存警告后通知发布了两次

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM