gpt4 book ai didi

cocoa - 比 DELEGATE_TRY_PERFORM_SELECTOR_WITH_SELF 更好的名称

转载 作者:行者123 更新时间:2023-12-03 18:00:48 25 4
gpt4 key购买 nike

我的项目中有很多 View Controller ,它们只是重定向到其委托(delegate)。所以我给它做了一个定义,但我对它的名字不太满意。

你会如何命名它或者你会以其他方式来做它?

我也遇到委托(delegate)可能返回对象或获取对象的情况多个参数。

<小时/>
// 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:);
}

最佳答案

为什么不在 UIViewController 上创建一个 Category 来为您提供该方法。

首先创建一个 .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];

注意:通常最好在类别中为方法名称添加前缀,这样它们就不会与任何内部方法发生冲突。

关于cocoa - 比 DELEGATE_TRY_PERFORM_SELECTOR_WITH_SELF 更好的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com