【发布时间】:2012-06-16 17:35:32
【问题描述】:
我有一组 Objective-C 类,它们被各种不同的类在不同的深度进行子分类。初始化整个对象后(所有子类的 init 函数都已完成),我需要运行“更新缓存”方法,然后根据需要被子类覆盖。
我的问题: 我的类树有各种不同的继承深度,没有一个地方可以放[self UpdateCache],而且我可以确定没有没有被初始化的子类。唯一可能的解决方案是在每个类初始化之后调用 [super init],以便始终最后调用父类。我想避免这种情况,因为这违反了编写 Objective-C 的所有准则。这个问题有什么干净的解决方案吗?
这是一个示例代码:
@interface ClassA : NSObject
-(void)UpdateCache
@end
@interface ClassB : ClassA
-(void)UpdateCache
@end
@interface ClassC : ClassB
-(void)UpdateCache
@end
现在对于实现,我们需要在知道所有子类都已初始化后以某种方式调用 UpdateCahce无论哪个类已被初始化
@implementation A
-(id)init
{
if(self = [super init])
{
// Placing [self UpdateCache] here would make it be called prior to
// B and C's complete init function from being called.
}
}
-(void)UpdateCache
{
}
@end
@implementation B
-(id)init
{
if(self = [super init])
{
// Placing [self UpdateCache] would result in UpdateChache not being
// called if you initialized an instance of Class A
}
}
-(void)UpdateCache
{
[super UpdateCache];
}
@end
@implementation C
-(id)init
{
if(self = [super init])
{
// Placing [self UpdateCache] would result in UpdateChache not
//being called if you initialized an instance of Class A or B
}
}
-(void)UpdateCache
{
[super UpdateCache];
}
@end
【问题讨论】:
-
冒着听起来很愚蠢的风险......在分配和初始化它之后,只为每个实例调用
[yourObj updateCache];是不是一个大问题? -
你的描述不好理解。 “一旦整个对象被初始化”?你的意思是整个类树?
updateCache是方法还是函数?是类方法,还是每个子类都实现的实例方法?为什么一个实例会关心树中的其他类——也就是说,为什么你不能在每个子类的init末尾调用这个方法? -
@HachiEthan - 这是我目前正在使用的解决方案,但我正在寻找更清洁的东西。实际上,我在很多地方都遇到过同样的问题,我想看看是否有任何通用的解决方案
-
@JoshCaswell - 此更新缓存功能是一项非常昂贵的操作,这就是缓存其结果的原因。如果我在每个子类中都调用它,那么在每一步调用它都会导致为相同的数据生成最多 4 次信息。
-
你所描述的仍然不清楚。你说它是一个“函数”(应该是“方法”,我假设)被“子类覆盖”,但你似乎也说它只需要为整个类树调用一次。您的描述很混乱,您没有解决我原始评论中的任何问题。请详细说明您的设计并更具体;也许发布一些虚拟代码。
标签: iphone objective-c