Using weak self in dispatch_async function
self.myQueue = dispatch_queue_create("com.biview.core_data", NULL);
dispatch_async(self.myQueue, ^(void){ if (!self.var1) {
self.var1 = ...;
}
dispatch_async(dispatch_get_main_queue(), ^(void) {
if ([self.var2 superview]) {
[self.var2 removeFromSuperview];
}
[self.Label setText:text];
});
});
do I need to use __weak self. Because I read that in some cases dispatch_async not need a __weak self.
=========== 이상 문제 ==========================
========= 다음은 답입니다 ===========================
Assuming, self is an object pointer to a UIViewController. Things to consider:
In your scenario, where you capture self in the block which is dispatched on the main queue, you don't need to worry that bad things happen.
So, why? And what happens actually? Since self will be captured in the block which is dispatched asynchronously, self will be implicitlyretained, and released again when the block has been finished.
That means, the life-time of self will be extended up until after the block finishes. Notice that yoursecond block is dispatched on the main thread, and it's guaranteed that self is still alive when that block gets executed.
This "extended life"above, might be a desired feature of your program.
If you explicitly don't want to extend the life-time of the UIViewController object,
and instead want the block - when it finally executes - check whether this UIViewController object does still exist at all, you can use a __weak pointer of self. Note that the block gets eventually executed, no matter whether the UIViewController is still alive or has been deallocated in the mean time.
You might want the block doing "nothing"if the UIViewController has been deallocated before the block will get executed:
MyController* __weak weakSelf = self;
dispatch_async(queue, ^{
MyController* strongSelf = weakSelf;
if (strongSelf) {
...
} else { // self has been deallocated in the meantime.
}
});
http://stackoverflow.com/questions/21987067/using-weak-self-in-dispatch-async-function
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.