我的项目中有很多viewcontrollers只是重定向到它的委托。 所以我已经为它做了一个定义,但我对它的名字并不高兴。
你会如何命名,或者你会以另一种方式进行命名?
我也有委托可以返回对象或采取的情况 多个论点。
// 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:);
}
答案 0 :(得分:1)
为什么不在Category
上创建UIViewController
来为您提供该方法。
首先创建一个.h
+ .m
文件。约定通常是使用您要添加类别的类的名称然后使用+
然后使用您想要调用的类。对于这个例子,我会保持简单(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
然后,您可以将此文件导入到您希望使用此方法的任何位置(或者如果在整个项目中使用它,请考虑.pch
)。现在,只要您进入UIViewController
子类(已导入UIViewController+additional.h
),您就可以调用方法
[self MYsafePerformSelectorOnDelegate:@selector(closeTab:) withObject:self];
注意:通常最好在方法名称前加上类别,以便它们与任何内部方法冲突的可能性更小。