iOS performSelector with multiple parameters

Guides | Tutorial By 2 years ago

On iOS the built in convenience method performSelector method call only allows for up to 2 parameters.

- (void) aMethod
{
	[self performSelector:@selector(doSomethingWithObject:otherObject:) withObject:@(1) withObject:@(2)];
}

- (void) doSomethingWithObject:(id) object otherObject:(id) otherObject
{
	//	Code here
}

You may find a situation where you want to use more than 2 parameters.

This can be done like so:

- (void) anotherMethod
{
	id target = self;
	SEL selector = @selector(doSomethingElseWithObject:otherObject:yetAnotherObject:);
	
	//	First first and second arguments are for the target and selector,
	//	the remaining argument types match those of the selector
	typedef void (*MethodType)(id, SEL, id, id, id);
	MethodType methodToCall = (MethodType)[target methodForSelector:selector];
	methodToCall(target, selector, @(1), @(2), @(3));
}

- (void) doSomethingElseWithObject:(id) object otherObject:(id) otherObject yetAnotherObject:(id) yetAnotherObject
{
	//	Code here
}