ios - NotificationCenter 观察者使用 ARC 阻止 dealloc

标签 ios iphone objective-c automatic-ref-counting nsnotificationcenter

我正在尝试调试我最近转换为使用 ARC 的项目。 我很难确定为什么对象没有被释放并保留在内存中(有没有一种简单的方法可以查看是什么引用将对象保留在内存中?)

通知中心链接似乎有一个问题。 在 viewDidLoad 上,我注册了三个通知:

[notificationCenter addObserverForName: kAudioPlaybackStart
                                object: nil
                                 queue:[NSOperationQueue mainQueue]
                            usingBlock:^(NSNotification *note) {
                                [self handle_PlaybackStateStart:nil];
                            }];
[notificationCenter addObserverForName: kAudioPlaybackStop
                                object: nil
                                 queue:[NSOperationQueue mainQueue]
                            usingBlock:^(NSNotification *note) {
                                [self handle_PlaybackStateStop:nil];
                            }];
[notificationCenter addObserverForName: kAudioPlaybackPause
                                object: nil
                                 queue:[NSOperationQueue mainQueue]
                            usingBlock:^(NSNotification *note) {
                                [self handle_PlaybackStatePause:nil];
                            }];

然后,当 viewController 完成后,我调用一个函数 unLoad:

- (void) unLoad {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    _mediaPlayerHelper = nil;
    _article = nil;
    _tableView = nil;
}

我有一个单独的函数的原因是除非所有对象都被释放,否则不会调用 viewDidUnload,所以我需要一些东西来释放它们。目前我在 viewDidDisappear 上调用它们。

然而,当注释掉观察者时,代码工作正常(并且 View 卸载),但是对于观察者它似乎不起作用并且 View 保留在内存中。有什么建议吗?

最佳答案

因为您正在使用带有 block 参数的通知方法,并且您在 block 中使用了对 self 的强引用。您应该使用使用回调选择器的观察方法(因此没有捕获)或创建对 self__weak 引用以在 block 中使用。

关于ios - NotificationCenter 观察者使用 ARC 阻止 dealloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021350/

相关文章:

javascript - Cordova/Phonegap为不同页面设置不同的设备方向

iphone - 在 iPhone 中添加自定义 AnnotationView

ios - 在 iOS 上,有没有办法在使用 UIGraphicsBeginImageContextWithOptions 创建 ImageContext 后获取它的大小?

iPhone - 行为类似于 UIViewController 的 UIView

ios - 扩展程序-错误(Swift3)

iphone - 如何将 NSArray 存储到 plist 或数据库中?

objective-c - iTunes Connect 崩溃报告 - UINibDecoderDecodeObjectForValue

iphone - JSON 框架没有隐藏的 API?

ios - UIKit:查看 Controller 自动加载 nib 文件

ios - 避免 3D 节点被切割