ios – 如何在dealloc方法中引用__weak self

我在一个名为“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];
   }
}

不知道为什么它在dealloc方法中失败,因为“self”仍然存在

当我将代码更改为

__typeof__(self) strongSelf = self; //everything works fine
__weak __typeof__(self) weakSelf = strongSelf; (or "self") BAD_INSTRUCTION error

错误发生在第二行

解决方法

只是为了让“你不应该”或“你不能”成为其他好答案的一部分
更确切:

用于存储弱引用的运行时函数是objc_storeWeak()和
Clang/ARC documentation州:

id objc_storeWeak(id *object,id value);


If value is a null pointer or the object to which it points has begun
deallocation,object is assigned null and unregistered as a __weak
object. Otherwise,object is registered as a __weak object or has its
registration updated to point to value.

由于self对象已经开始释放,所以weakSelf应该设置为NULL
(因此没有任何用处).

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...