NSNotificationCenter崩溃我的应用程序

时间:2016-01-27 14:13:07

标签: ios objective-c cocoa-touch nsnotificationcenter

我添加了一个NSNotificationCenter观察者,它在两个不同的视图控制器上调用两个具有相同名称的选择器。

它可以工作,但是当我运行应用程序时,它会崩溃并显示以下错误消息:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x18)

Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

Image

任何人都知道它崩溃的原因?谢谢!

我的代码:

fetchFromParse

-(void)sendAllStores
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"getStoresArrays" object:nil userInfo:self.storesDict];
}

firstVC.m

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getStoresArrays:) name:@"getStoresArrays" object:nil];
}

-(void)getStoresArrays:(NSNotification*)notification
{
    NSLog(@“Working”);  
}

secondVC.m

-(void)prepareArrays
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getStoresArrays:) name:@"getStoresArrays" object:nil];
}
-(void)getStoresArrays:(NSNotification*)notification
{
    NSLog(@“Working”);
}

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.secVC=[[secondVC alloc] init];
    [self.secVC prepareArrays];

    fetchFromParse *fetchFromParseObj=[[fetchFromParse alloc] init];
    [fetchFromParseObj getStoresFromParse];

    Return YES;
}

4 个答案:

答案 0 :(得分:2)

通知崩溃

如果您尝试关闭视图控制器而不删除观察者,通常可能会看到此类崩溃。所以Patil先生提供的部分答案是绝对必要的。您的用例将根据您移除观察者的位置和方式而有所不同。如果你过早删除它,如果你试图引用任何相关的对象,你可能会崩溃。

因此,您可能希望删除self.storesDict对象,或者在使用它之前至少验证它是否为零。

调试

这是使用Xcode进行调试的quick tutorial。它适用于旧版本,但它可以让您快速上手。您还可以查看Apple docs以获取有关收集崩溃日志的更多信息。

日志

您应该转到报告导航器并复制一些日志,以便我们确定问题的更准确原因。您可以在错误代码之前添加断点,然后逐步解决问题。如果没有别的话,复制调试控制台。

获取崩溃日志

您可以打开Xcode,在Window菜单中选择Devices。选择您连接的设备(iPhone / iPad),然后单击“查看设备日志”按钮。从列表中选择您的应用名称/崩溃日期。将数据复制到问题中。

更多信息

您提供的有关崩溃的信息越多,我们就越有可能为您提供帮助。我怀疑答案是你要么想要在正确的时间访问nil或者没有释放观察者的东西。当您的视图消失但是您没有提供足够的信息来表明这一点时,可能不适合释放观察者。

不同的视图控制器如何协同工作?你确定通知导致崩溃?在帖子通知和每个选择器中放置一个断点,然后调试应用程序直到它崩溃。您需要确定崩溃之前的条件。如果您在更新问题时通知我,我会优化此答案。

答案 1 :(得分:1)

我要做的第一件事是进行全局搜索,并确保没有其他类正在收听该通知。然后我会确保在您为该通知添加观察者的类中执行以下操作:

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

答案 2 :(得分:0)

添加此

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    //Has to be unregistered always, otherwise nav controllers down the line will call this method
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
希望它有所帮助。

答案 3 :(得分:0)

你确定在主线程上调用了'addObserver','postNotification'和'removeObserver'总是吗?

请仔细检查:

if ([NSThread isMainThread])
相关问题