简体   繁体   English

如何使用NSInvocation创建我自己的类的实例?

[英]How to create instance of my own class using NSInvocation?

I am trying to create a new instance of my custom class (custom init method call, with a BOOL parameter) dynamically. 我试图动态创建自定义类的新实例(自定义init方法调用,带有BOOL参数)。 How can I use NSInvocation to do that? 如何使用NSInvocation做到这一点?

This is what I have so far: 这是我到目前为止的内容:

NSMethodSignature* signature = [NSClassFromString(className) instanceMethodSignatureForSelector: sel];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: signature];
[invocation setTarget: [NSClassFromString(className) alloc]];
[invocation setSelector:sel];
[invocation setArgument:&value atIndex:2];
[invocation invoke];
[invocation getReturnValue:&obj];

Above sample throws error in line [invocation invoke]; 上面的示例在[invocation invoke];行中引发错误[invocation invoke]; error is "message sent to deallocated instance" . 错误是"message sent to deallocated instance"

Your code doesn't work because the NSInvocation doesn't retain the target or any arguments unless you tell it to (with retainArguments ). 您的代码无法正常工作,因为NSInvocation不会保留目标或任何参数,除非您告知目标对象或参数(带有retainArguments )。 So, you alloc an instance and then it gets destroyed before you invoke the NSInvocation . 因此,您alloc一个实例,然后在invoke NSInvocation之前将其销毁。

Alternatively, create an instance variable and store the alloc 'd instance there, then pass that to the NSInvocation . 或者,创建一个实例变量,并将alloc实例存储在那里,然后将其传递给NSInvocation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM