简体   繁体   中英

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. How can I use NSInvocation to do that?

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]; error is "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 ). So, you alloc an instance and then it gets destroyed before you invoke the NSInvocation .

Alternatively, create an instance variable and store the alloc 'd instance there, then pass that to the NSInvocation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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