2012-01-23 60 views
0

我在我的应用中遇到了NSNotificationCenter的观察者问题。在NSNotificationCenter中添加2个观察员在1个班级中

我AppDelegate类有2个服务类获得通过URL数据,要求ExhibitionService & NewsService。

这2个服务类本身使用一个Queueloader类。

当我写2观察员在我AppDelegate类听服务加载操作,它会返回错误和崩溃。

APP委托类

ExhibitionLoaderService *exhibitionService = [[ExhibitionLoaderService alloc] init]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exhitibionServiceComplete :) name:**CserviceComplete** object:nil]; 

[exhibitionService load]; 

NewsLoaderService *newsService = [[NewsLoaderService alloc] init]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsServiceComplete :) name:**CserviceComplete** object:nil]; 

[newsService load]; 

ExhibitionLoaderService.m & NewsLoaderService具有相同的方法

-(void)load 
{ 
    Queueloader *que = [[Queueloader alloc] initWithPath:CExhibitionURLPath isVerbose:NO]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didQueComplete:) name:CdidQueueloaderComplete object:nil]; 
    [que startOperation]; 
    [que release]; 
} 

ERROR I GOT

[[NSNotificationCenter defaultCenter] postNotificationName:**CdidQueueloaderComplete** object:results]; 

2服务类具有CdidQueueloaderComplete ...问题是关于观察家但如何?什么? PS:编程接收信号EXC_BAD_ACCESS。

谢谢。

回答

1

有多个观察员有相同的通知没有问题。你描述的问题听起来很像它与观察者的一生有关。

如果您解除对其仍然登记听通知的对象,该NSNotificationCenter不知道。如果将来发出通知,中心会将其转发给它认为仍在监听的对象(但已经消失),并且您会发生崩溃。

解决这个问题是要确保你的对象作为观察员删除它被破坏之前。有两种方法可以做到这一点:

  • 往往你就会知道,当一个对象应该启动或停止监听通知,你可以确保你删除它作为观察员时,应立即停止(例如,也许视图控制器应该开始监听模型更新时,他们的观点似乎并停止监听时,他们的看法消失)
  • 其他时间,对象可以其自己的通知生命周期后看:也许你可以开始在初始化器监听和停止-dealloc听。

无论你做什么,你需要平衡添加观察员和删除观察员,以便当一个对象消失时,它不再注册通知中心。

+0

在这个例子中,我做了很快的一些行代码。当它运行时,你会看到我的问题是什么..这是链接,如果你想检查它。 www.mobilbuzz.com/stackoverflow/NotificationCenterExample.zip – selcuk

相关问题