【问题标题】:Delegate with async callback使用异步回调进行委托
【发布时间】:2023-03-24 16:23:01
【问题描述】:

我在这里发现了很多关于委托技术的问题,并尝试了很多变体,但仍然有 BAD_ACCESS 异常。

我的应用通过 NSUrlConnection 从网络异步接收数据。 我正在使用带有委托给 VC 的特殊数据交换对象。

使用 NSZombies 调试选项,我收到消息:[MyViewController tableView:titleForHeaderInSection:]: message sent to deallocated instance 0x79698490.

VC:

@property DataManager *man;

- (void)viewDidLoad {
 ...
 man = [[DataManager alloc] initWithDelegate:self];
 ...
}

- (void) myDelegateSelector {
 // DataManager call this method when data is ready
... save data ...
 _tableView reloadSections ... // refresh content
}

数据管理器:

@property (weak, nonatomic) id <DataManagerDelegate> delegate;

- (id) initWithDelegate:(id <DataManagerDelegate>)delegate {
 ...
 _delegate = delegate; 
}

- (void) receiveSomeData {
 ...
 dispatch_async(dispatch_get_global_queue(0, 0), ^{
        ... receive data work in global queue
        if (_delegate)
            // going back to the main queue cause need to change on screen data
            dispatch_async(dispatch_get_main_queue(), ^{
                    if ([_delegate respondsToSelector:@selector(myDelegateSelector:)])
                        [_delegate myDelegateSelector];
            });
    });
}

【问题讨论】:

  • 这意味着你的 MyViewController 在你试图让它做某事时被释放。谁创建/管理您的 MyViewController?您的代码没有显示那是什么控制器。
  • 是的,我知道。 VC 由父控制器创建。当用户快速点击“返回”按钮时,数据仍在加载,有时会出现异常。

标签: ios objective-c asynchronous delegates automatic-ref-counting


【解决方案1】:

在这种情况下,您应该始终在 dealloc 方法中删除委托。对于您的视图控制器:

-(void)dealloc {
    man.delegate = nil;
}

您已经检查了 if (_delegate)。当您的 VC 快速关闭时,如果不将其设置为 nil,_delegate 将被释放但不是 nil。

【讨论】:

  • _delegate 是弱引用,为什么 VC deallocate 时不为 nil?
  • 我自己不太确定机制,但这里有一些解释。 stackoverflow.com/questions/20653841/… 如果你添加断点,你会看到委托被释放但不是零,并且是某种无效但存在的内存指针。如果委托非零,它实际上会尝试引用委托并使其执行调用,这将导致崩溃。
【解决方案2】:

问题成功解决。

解决方案:

VC 代码:

- (void) dealloc 
{
  _tableview.datasource = nil;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多