这有一种响应者链的感觉,但不同之处在于,响应者链是专门针对 View 和 View Controller 定义的操作。
嗯,我需要通过几个不相关的类传递方法调用,并且对 Objective-C 相当陌生,我不确定定义一个协议(protocol),然后在每个类上实现该协议(protocol)是否是一种黑客行为。调用需要经过的类。
例如...
ClassA 是 ClassB 的委托(delegate)。
ClassB 是 ClassC 的委托(delegate)
...因此有“响应者链”的感觉。
这对于将调用从 C 传递到 B 再到 A 的代码有意义吗?
我假设在某个时候,当链变得太长时,您可能会推荐一种通知技术,但我不知道推荐的长度可能是多少。
@protocol DidSomething
-(void)userDidSomething:(NSString*)something
@end
ClassA <DidSomething>
-(void)userDidSomething:(NSString*)something
{
NSLog(@"The user did something %@",something);
}
ClassB <DidSomething>
-(void)userDidSomething:(NSString*)something
{
[self.delegate userDidSomething:something];
}
ClassC <DidSomething>
-(void)thatWasInteresting
{
[self.delegate userDidSomething:@"Cool"];
}
最佳答案
不。没有错。避免潜在的复杂性。
如果需要,您可以将其定义为协议(protocol)。或者您可以将其定义为公共(public)抽象父类(super class)(如果可能)。
协议(protocol)通常是当今的主流方式,使用 @Optional
需要使用 respondsToSelector:
测试(或 conformsToProtocol:
) .
总而言之,您应该非常小心地使用这种模式。具体来说,它暗示了很多关于应用程序架构的信息,因此,您希望确保该架构是健全的。
关于ios - 通过几个不相关的类传递方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665300/