[英]Memory issue when calling dispatch_async with local variable
I am having issues in code when calling dispatch_async. 调用dispatch_async时,我在代码中遇到问题。 I think that issue is due to ARC reclaiming the object, before it is used in a block, as the method that dispatches it finishes.
我认为这个问题是由于ARC在分块中使用该对象之前回收了该对象,因为分派该对象的方法完成了。
- (void) method:(SomeClass *) someClass {
// local variable
NSNumber *someValue = someClass.somePropertyOnManagedObject;
dispatch_async(queue, ^() {
/* call some singleton object passing variable
* when access the variable, reference is nil
*/
[[DashboardFacade sharedInstance] someMethod:someValue];
});
}
After having looking through much documentation, I conclude 看完许多文档后,我得出结论
I think that the solution is to use __block
modifier such that ARC retains the variable. 我认为解决方案是使用
__block
修饰符,以便ARC保留变量。
My question is 我的问题是
__block
will resolve the problem and not introduce other problems? __block
可以解决问题,而不会引入其他问题? Is the above technically correct, eg using __block will resolve the problem and not introduce other problems?
以上技术上是否正确,例如,使用__block可以解决问题,而不会引入其他问题?
Yes it's technically correct, __block
, on ARC, allows you to change the variable (in this case to where its pointing, since it's a NSNumber *
), that was declared outside the block context. 是的,它在技术上是正确的,在ARC上,
__block
允许您更改在块上下文之外声明的变量(在本例中为变量指向的位置,因为它是NSNumber *
)。
Why can't I find this anywhere on the internet/google?
为什么我不能在Internet / Google上的任何地方找到它?
I think the problem is not related to this particular place of your code, but something else. 我认为问题与代码的特定位置无关,而是其他原因。
someValue
inside the block can be nil only if it is nil after this assignment: 仅在此分配之后为零时,块内的
someValue
才能为零:
NSNumber *someValue = someClass.somePropertyOnManagedObject;
Blocks retain objects that are being captured by the blocks as a result of those variables being used inside the blocks. 块保留由于块内使用的那些变量而被块捕获的对象。 And it doesn't matter if it is self or a local variable from the scope that is visible to the block.
而且它是self还是块可见的作用域中的局部变量都没有关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.