我在一个名为“cancelAllPendingDownloads”的各个地方调用了一个方法
这是一种取消各种作业和更新内部计数器的通用方法.
这是一种取消各种作业和更新内部计数器的通用方法.
-(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.