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

Dhe*_*j D 4 singleton objective-c nsnotificationcenter ios

当我将 self 作为观察者传递,同时在单例对象创建类方法中添加 NSNotification 时,我的应用程序崩溃了。请查看下面的代码。

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

    }
    return downloadThumbnail;
}   
Run Code Online (Sandbox Code Playgroud)

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

小智 5

看看“self”指针总是为您提供当前类对象的引用,但如果您在类方法下使用此指针,则意味着它将为您提供类指针,即“DownloadThumbnail”。因此,每当通知触发时,它都会调用类似于下面的代码。

[DownloadThumbnail connectedToInternet];
Run Code Online (Sandbox Code Playgroud)

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

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

[[NSNotificationCenter defaultCenter] addObserver:downloadThumbnail selector:@selector(connectedToInternet) name:NotifyInternetConnection object:nil];
Run Code Online (Sandbox Code Playgroud)

现在尝试一下,它不会崩溃:)

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