初始化所有子类后如何执行操作?

时间:2012-06-13 17:36:51

标签: iphone objective-c

我有一系列Objective-C类,它们可以通过各种不同的类在各种不同的深度进行细分。一旦整个对象被初始化(所有子类init函数都已完成),我需要运行一个“更新缓存”方法,然后根据需要由子类覆盖。

我的问题: 对于我的类树有各种不同的继承深度,没有一个地方可以放置[自我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

4 个答案:

答案 0 :(得分:3)

为什么不在初次使用之前更新它,而不是在init之后立即更新缓存?也许您可以在init中将布尔实例变量cacheIsDirty设置为TRUE。然后,如果缓存是脏的,则缓存的getter首先调用updateCache。假设您总是使用getter并且从不直接使用实例变量(这是Objective-C中的好习惯),客户端不应该注意到差异。

答案 1 :(得分:1)

您的子类是否需要唯一的init方法签名? (例如,初始化对象所需的子类特定参数)如果不是,则遵循简单的工厂类设计模式可以正常工作。

添加父/基类的示例:

+(id)buildSelf {
    YourParentClass* obj = [[[self alloc] init] autorelease];
    if (obj) {
        [obj updateCache];
    }
    return obj;
}

为所有子类添加参数,如果需要的话。

同样,如果您的子类需要支持唯一的init方法签名,那么这将无法正常工作。

答案 2 :(得分:0)

声明一个虚方法并在需要时调用它....

由于这是客观的,请参阅Implement a pure virtual method in Objective-C

答案 3 :(得分:0)

是的,我回答了一个类似的问题...... 您可以向对象实例添加“钩子”/“代理”以覆盖-forwardInvocation:选择器并执行您想要的操作。最初的问题是here,我对它的回答是被接受的。

相关问题