如何在dealloc方法中引用__weak self

Avn*_*arr 8 weak-references objective-c dealloc ios automatic-ref-counting

我有一个名为"cancelAllPendingDownloads"的各种地方调用的方法这是取消各种作业和更新内部计数器的一般方法.

在dealloc方法中调用时会出现问题

-(void)dealloc
{
  [self cancelAllPendingDownloads]; // want to cancel some jobs
}

-(void)cancelAllPendingDownloads // updates some internals
{
    __weak __typeof__(self) weakSelf = self; // This line gets a EXC_BAD_INSTRUCTION error in runtime
   for(Download *dl in self.downloads)
   {
      dl.completionHandler = ^{ // want to replace the previous block
        weakSelf.dlcounter--;
      }
      [dl cancel];
   }
}
Run Code Online (Sandbox Code Playgroud)

不确定为什么它在dealloc方法中失败,因为"self"仍然存在

当我将代码更改为

__typeof__(self) strongSelf = self; //everything works fine
__weak __typeof__(self) weakSelf = strongSelf; (or "self") BAD_INSTRUCTION error
Run Code Online (Sandbox Code Playgroud)

错误发生在第二行

Mar*_*n R 16

只是为了使"你不应该""你不能"更好地回答其他好的答案:

用于存储弱引用的运行时函数是objc_storeWeak(),并且 Clang/ARC文档指出:

id objc_storeWeak(id *object, id value);

...如果value是空指针或它指向的对象已开始解除分配,则将对象指定为null并取消注册为__weak对象.否则,将对象注册为__weak对象或将其注册更新为指向值.

由于self对象已经开始解除分配,因此weakSelf应该设置为NULL (因此没有任何用处).

但是,在这种情况下,似乎有一个错误(如http://www.cocoabuilder.com/archive/cocoa/312530-cannot-form-weak-reference-to.html所述)objc_storeWeak(),而不是返回NULL.