Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this questionI have a lot of viewcontrollers in my project that just redirects to its delegate. So I have made a define for it, but I'm not so happy about it's name.
How would you name it or would you do it in another way?
I also have situations where the delegate may return an object or take multiple arguments.
// the problem is highly repetitive code
-(void)switchToNextTab:(id)sender {
SEL sel = @selector(switchToNextTab:);
if([m_delegate respondsToSelector:sel]) {
[m_delegate performSelector:sel withObject:self];
}
开发者_如何学运维}
-(void)switchToPrevTab:(id)sender {
SEL sel = @selector(switchToPrevTab:);
if([m_delegate respondsToSelector:sel]) {
[m_delegate performSelector:sel withObject:self];
}
}
-(void)closeTab:(id)sender {
SEL sel = @selector(closeTab:);
if([m_delegate respondsToSelector:sel]) {
[m_delegate performSelector:sel withObject:self];
}
}
// my solution.. which I need a better name for
#define DELEGATE_TRY_PERFORM_SELECTOR_WITH_SELF(selector_name) \
do { \
SEL sel = @selector(selector_name); \
if([m_delegate respondsToSelector:sel]) { \
[m_delegate performSelector:sel withObject:self]; \
} \
} while(0);
-(void)switchToNextTab:(id)sender {
DELEGATE_TRY_PERFORM_SELECTOR_WITH_SELF(switchToNextTab:);
}
Why not create a Category
on UIViewController
to give you that method.
Start by creating a .h
+ .m
file. The convention is normally to use the name of the class you are adding the category to then a +
then whatever you want to call it. For this example I'll keep it simple (UIViewController+additional
)
// UIViewController+additional.h
@interface UIViewController (additions)
- (void)MYsafePerformSelectorOnDelegate:(SEL)selector withObject:(id)anObject;
@end
// UIViewController+additions.m
@implementation UIViewController (additions)
- (void)MYsafePerformSelectorOnDelegate:(SEL)selector withObject:(id)anObject
{
if([m_delegate respondsToSelector:selector]) {
[m_delegate performSelector:selector withObject:anObject];
}
}
@end
You then import this file wherever you want to use this method (or consider the .pch
if it is used throughout your whole project). Now anytime you are in a UIViewController
sub class (that has the UIViewController+additional.h
imported) you can call the method
[self MYsafePerformSelectorOnDelegate:@selector(closeTab:) withObject:self];
NOTE: It is normally a good idea to prefix your method names in categories so that they have less chance of clashing with any internal methods.
精彩评论