在运行后台线程时释放对象时发生崩溃

时间:2022-05-12 16:03:55

I have a set of objects, init'd and owned by a view controller. The view controller starts a fetchData method in each of these objects, which runs in a background thread and then, when it's done, returns the main thread and changes a property - self.dataFetchComplete, which the view controller is observing.

我有一组对象,由视图控制器初始化并拥有。视图控制器在每个对象中启动一个fetchData方法,这些对象在后台线程中运行,然后,当它完成时,返回主线程并更改属性 - self.dataFetchComplete,视图控制器正在观察它。

dispatch_async(dispatch_get_main_queue(), ^{        
    self.dataFetchComplete = YES;
});

If the view controller is deallocated before these objects are finished with this method, when it hits the self.dataFetchComplete = YES; line, it crashes.

如果在使用此方法完成这些对象之前取消分配视图控制器,则当它到达self.dataFetchComplete = YES时;线,它崩溃了。

How can i stop it from crashing when trying to change this property after being deallocated.

在解除分配后尝试更改此属性时,如何阻止它崩溃。

EDIT: More info, and clarity.

编辑:更多信息,清晰度。

1 个解决方案

#1


1  

That block has a strong reference to self. The only way self could be deallocated is if you are over-releasing it elsewhere (as @Catfish_Man indicated).

那个街区强烈提到了自我。自我可以被释放的唯一方法是,如果你在其他地方过度释放它(如@Catfish_Man所示)。

  1. if you have a crash, post the backtrace of the crash

    如果你遇到了崩溃,请发布崩溃的回溯

  2. if you have an over-release crash, use Instruments to track all retain/release events on the object.

    如果发生过度释放崩溃,请使用Instruments跟踪对象上的所有保留/释放事件。

  3. run the analyzer and fix any problems it indicates.

    运行分析仪并修复它指出的任何问题。

#1


1  

That block has a strong reference to self. The only way self could be deallocated is if you are over-releasing it elsewhere (as @Catfish_Man indicated).

那个街区强烈提到了自我。自我可以被释放的唯一方法是,如果你在其他地方过度释放它(如@Catfish_Man所示)。

  1. if you have a crash, post the backtrace of the crash

    如果你遇到了崩溃,请发布崩溃的回溯

  2. if you have an over-release crash, use Instruments to track all retain/release events on the object.

    如果发生过度释放崩溃,请使用Instruments跟踪对象上的所有保留/释放事件。

  3. run the analyzer and fix any problems it indicates.

    运行分析仪并修复它指出的任何问题。