Reputation: 202
I have a couple of methods that do nearly the same thing, the only difference is the selector they use, which is being passes as an argument. But the selectors use different number of arguments, raging from 0 to 2, which are also being passed as an argument. It looks like this (SupportClass is a class from which I call a method that's to be used in random methods):
-(void) RandomMethod: (SEL) selector {
// some actions here
[SupportClass performSelector:selector];
}
-(void) RandomMethod2: (SEL) selector withObject: object {
// the same actions here
[SupportClass performSelector:selector withObject: object];
}
-(void) RandomMethod2: (SEL) selector withObject1: object1 withObject2: object2 {
// again - the same actions
[SupportClass performSelector:selector withObject1: object1 withObject2:object2];
}
But since they all do the same I would like to find a more generic solution which would enable to compress it into one method, which would also enable me to use it for selectors with more arguments (which I most likely won't need, but still I guess it would look nice). Does anyone know how to do this and would be kind enough to tell me?
Upvotes: 0
Views: 110
Reputation: 122518
Blocks is the best way to do it.
Another general solution is to use forwardInvocation:
. Instead of implementing these methods, you implement forwardInvocation:
on some proxy object, and then the caller calls the method they want to call like normal on this proxy object (i.e. they don't separate out selector, etc. They pretend that this object has these methods and calls the method with the arguments.). Then in the forwardInvocation:
, it can invoke the invocation on SupportClass
.
Upvotes: 0
Reputation: 1866
block solution seems best,
you can also modify your methods to only receive a NSDictionary as the only argument, and pass your data with this NSDictionary
(void)methodA:(NSDictionary *)data;
(void)methodB:(NSDictionary *)data;
Upvotes: 0
Reputation: 130191
Instead of passing selectors + parameters, pass blocks of code. Your code seems like a perfect example for a completion block.
Example:
- (void)someMethodWithCompletionBlock:(void(^)())completionBlock {
//do something
completionBlock();
}
[myObject someMethodWithCompletionBlock:^{
[SupportClass performSelector:selector];
};
Upvotes: 2