Objective-C: How to call performSelector with a BOOL typed parameter?

Is there any way to send a BOOL in selector ?

[self performSelector:@selector(doSomething:) withObject:YES afterDelay:1.5];

Or I should use NSInvocation? Could somebody write a sample please ?


In the case that you cannot alter the target-method signature to accept a NSNumber in place of a BOOL you can use NSInvocation instead of performSelector:

MyTargetClass* myTargetObject;
BOOL myBoolValue = YES; // or NO

NSMethodSignature* signature = [[myTargetObject class] instanceMethodSignatureForSelector: @selector( myMethodTakingBool: )];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: signature];
[invocation setTarget: myTargetObject];
[invocation setSelector: @selector( myMethodTakingBool: ) ];
[invocation setArgument: &myBoolValue atIndex: 2];
[invocation invoke];

you can use NSNumber to wrap bools types:

BOOL myBool = YES;
NSNumber *passedValue = [NSNumber numberWithBool:myBool];
[self performSelector:@selector(doSomething:) withObject:passedValue afterDelay:1.5];

and in the selector, to get the bool value, you use:

BOOL value = [recievedObject boolValue];

The simplest way is as follows:

If you have method

-(void)doSomething:(BOOL)flag

and want to performSelecor with flag=NO use

[object performSelector:@selector(doSomething:) withObject:nil];

In case of flag=YES you can send any object, for example, @YES - number from bool

 [object performSelector:@selector(doSomething:) withObject:@YES];

Note: don't use @NO ! Only nil will be interpreted as NO in your method with bool argument.


use dispatch_after in main thread like this:

dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (_animationDuration+1) * NSEC_PER_SEC);
dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    [self completeAnimation:NO];
});