[英]How can I solve this memory Leak? NSInvocation
-(void)invokeMethod
{
NSMethodSignature * sig = [[source class] instanceMethodSignatureForSelector:@selector(mySelector:)];
NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setTarget:myTarget];
[invocation setSelector:@selector(mySelector:)];
MySubClassOfNSInvocationOperation * command = [[[MySubClassOfNSInvocationOperation alloc] initWithInvocation:invocation] autorelease];
//setArgument retains command
[invocation setArgument:&command atIndex:2];
//addOperation retains command until the selector is finished executing
[operationQueue addOperation:command];
}
-(void)mySelector:(MySubClassOfNSInvocation*)command
{
//Do stuff
}
I don't know exactly what is happening, but NSInvocation
& MySubClassOfNSInvocationOperation
are leaking 我不知道到底发生了什么,但是
NSInvocation
和MySubClassOfNSInvocationOperation
正在泄漏
When I remove the line: 当我删除行时:
[invocation setArgument:&command atIndex:2];
It doesn't leak, so some kind of problem with passing command as an argument. 它不会泄漏,因此将命令作为参数传递时会出现某种问题。
You probably have a reference counted loop... a situation where command
retains invocation
and invocation
retains command
and neither wants to release until their own dealloc
method -- leading to a situation where they never get freed. 您可能有一个引用计数循环...一种情况,其中
command
保留invocation
而invocation
保留command
并且都不希望在自己的dealloc
方法之前释放-导致它们从未被释放。
You need to decide which of the two is hierarchically senior to the other and make sure that the junior object does not retain the senior. 您需要确定两个对象中哪个哪个对象在层次结构上优先于另一个对象,并确保该下级对象不保留另一个对象。 Incidentally --
NSInvocation
won't retain arguments unless you call retainArguments
. 顺便说一句-
NSInvocation
,除非你调用不会保留参数retainArguments
。 Alternately, you can implement a close
method, manually telling one to release the other, breaking the cycle. 或者,您可以实现
close
方法,手动告诉一个释放另一个,从而中断循环。
I wrote the post " Rules to avoid retain cycles " after uncovering this exact issue with NSInvocation
in one of my own projects. 在我自己的一个项目中发现
NSInvocation
确切问题后,我写了“ 避免保留周期的规则 ”一文。
It seems that setArgument method retains buffer (in this case - your command object). 似乎setArgument方法保留了缓冲区(在这种情况下-您的命令对象)。 You can try to release command after setting.
设置后可以尝试释放命令。 But you should be care).
但您应该小心)。 My friend was confused when his app wasn't run on new iPhone OS, because he corrected Apple's leak by adding one line with additional release message.
当我的朋友的应用程序无法在新的iPhone操作系统上运行时,我的朋友感到困惑,因为他通过添加一行附加附加的发布消息来纠正了苹果的漏洞。 And when apple made correction in new OS, this line was the reason of crashing the app)
当苹果在新操作系统中进行更正时,此行是导致应用崩溃的原因)
What's with the extra ampersand on this line: 这行上的多余的&符号是什么:
[invocation setArgument:&command atIndex:2];
You're passing a pointer-to-a-pointer of your command. 您正在传递命令的指针。 That seems wrong to me.
对我来说这似乎是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.