使用ARC在自己的完成块中引用NSOperation对象 [英] Referencing an NSOperation object in its own completion block with ARC
问题描述
我很难将一些NSOperation代码转换为ARC.我的操作对象使用了一个完成块,该完成块又包含一个GCD块,用于更新主线程上的UI.因为我从自己的完成对象内部引用了操作对象,所以我使用__weak指针来避免内存泄漏.但是,在我的代码运行时,指针已设置为nil.
I'm having difficulty converting some NSOperation code to ARC. My operation object uses a completion block, which in turn contains a GCD block that updates the UI on the main thread. Because I reference my operation object from inside its own completion block, I'm using a __weak pointer to avoid a memory leak. However, the pointer is already set to nil by the time my code runs.
我将其范围缩小到此代码示例.有人知道我哪里出了问题,以及实现此目标的正确方法吗?
I've narrowed it down to this code sample. Anyone know where I went wrong, and the right way to accomplish this?
NSOperationSubclass *operation = [[NSOperationSubclass alloc] init];
__weak NSOperationSubclass *weakOperation = operation;
[operation setCompletionBlock:^{
dispatch_async( dispatch_get_main_queue(), ^{
// fails the check
NSAssert( weakOperation != nil, @"pointer is nil" );
...
});
}];
推荐答案
对此我不确定,但是正确的方法可能是在有问题的变量中添加__block,然后将其设置为nil块的末尾以确保将其释放. 请参阅此问题.
I'm not certain about this, but the correct way to do it is possibly to add __block to the variable in question, and then set it to nil at the end of the block to ensure that it is released. See this question.
您的新代码如下:
NSOperationSubclass *operation = [[NSOperationSubclass alloc] init];
__block NSOperationSubclass *weakOperation = operation;
[operation setCompletionBlock:^{
dispatch_async( dispatch_get_main_queue(), ^{
// fails the check
NSAssert( weakOperation != nil, @"pointer is nil" );
...
weakOperation = nil;
});
}];
这篇关于使用ARC在自己的完成块中引用NSOperation对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!