简体   繁体   中英

NSInvocation setSelector is throwing an exception

I have the following code which I'm testing:

NSString * parameterSignature = @"@:";
NSMethodSignature * signature = [NSMethodSignature signatureWithObjCTypes:[parameterSignature UTF8String]]; 
NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:@selector(aMethodWithNoParms)];

When the setSelector executes I get this error:

Name: NSInvalidArgumentException
File: Unknown
Line: Unknown
Reason: -[NSInvocation setArgument:atIndex:]: index (1) out of bounds [-1, 0]

I've been trolling the net looking for the reason why and not found it. It looks like it's trying to set the second parameter of the invocation which would be the selector, but the array is not long enough. I would have thought that the creation of the invocation would have setup the array.

I'm not sure how to fix this, anyone see what I've done wrong?

I thiink the first character of the C string should be the return type. So it should be

"@@:"

if the method returns an object. Your string defines a method with a return type of object and one parameter which is a selector. In fact, at the minimum you need the return type, the receiver type and the selector type.

See this discussion .

If your method doesn't return anything ie it has a void return type, then your method signature will be,

NSString * parameterSignature = @"v@:";

indicating void return type, self and _cmd .

You should preferably use methodSignatureForSelector: or instanceMethodSignatureForSelector: to get the method signature.

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