ios - 在 Singleton 方法中添加通知时将自身作为观察者传递时应用程序崩溃

标签 ios objective-c singleton nsnotificationcenter

当我将自己作为观察者传递给单例对象创建类方法中的 NSNotification 时,我的应用程序崩溃了。请查看以下代码。

+(DownloadThumbnail *)sharedDownloadThumbnailInstance{
    if(downloadThumbnail==nil){
        downloadThumbnail = [[DownloadThumbnail alloc]init];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectedToInternet) name:NotifyInternetConnection object:nil];

    }
    return downloadThumbnail;
}   

我花了大约 4 到 5 个小时来解决崩溃问题,但没有得到任何解决方案。

最佳答案

看起来“self”指针总是给你当前类对象的引用,但如果你在类方法下使用这个指针,这意味着它会给你类指针,即“DownloadThumbnail”。因此,无论何时触发通知,它都会调用类似于下面的代码。

[DownloadThumbnail connectedToInternet];

因为没有找到“connectedToInternet”的类方法,这就是它崩溃的原因。

所以你需要传递“downloadThumbnail”创建对象的引用,代码如下所示

[[NSNotificationCenter defaultCenter] addObserver:downloadThumbnail selector:@selector(connectedToInternet) name:NotifyInternetConnection object:nil];

现在试试,它不会崩溃:)

您也可以引用此链接 NSNotificationCenter: addObserver that is not self获取有关在 NSNotificationCenter 中将“ self ”作为观察者传递的更多详细信息。

关于ios - 在 Singleton 方法中添加通知时将自身作为观察者传递时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36643285/

相关文章:

ios - 针对 iOS 3.0 和 armv6/armv7 的应用程序的无效二进制架构

iOS8 模拟器 : Proxy authentication pop up not being shown

iphone - 是否允许在单例类中为变量定义属性和综合?

iphone - 切换icloud帐户时创建永久存储时应用程序崩溃

ios - 在 UIAlertController 文本字段中传递变量

C# - 是否可以通过使用接口(interface)来实现单例模式?

java - 不同对象的单例 JFrame

ios - 不确定为什么 NSURLSession 超时

ios - 如何在我使用 UIImagePickerController 拾取图像后从 PhotoLibrary 中删除图像

objective-c - 查找当前事件的 Finder 窗口/文件夹