-1

我以前遇到过这种需求。现在,我有一个每 0.1 秒调用一次的函数来检查已经过去了多少时间。如果它超过“总时间”(它从getTotalTime函数中检索),它就会停止。该getTotalTime方法在子项中被覆盖。每 0.1 秒调用一次的函数的代码也被覆盖了,但是使用的父类中的原始方法getTotalTime被调用 using super,只需要调用子类的方法getTotalTime而不是它自己的方法。这当然是问题所在。我可以从每个孩子的父母那里重写代码,但这似乎很愚蠢。一些谷歌搜索已经显示了其他语言的解决方案,但没有在 Objective-C 中。有没有办法做到这一点?如果没有,有哪些替代方案?

4

1 回答 1

4

每0.1秒调用一次的函数的代码也被重写了,但是父类中使用getTotalTime的原始方法是使用super调用的,只是它需要调用子类的getTotalTime方法而不是自己的方法。

你的问题很难解析,但听起来你有这样的东西:

@interface A : NSObject // the "parent" class
- (void) timerMethod;
- (NSDate*) getTotalTime;
// other methods as necessary
@end

@interface B : A // the "child" class
// only has overrides of A's methods
@end

@implementation A
- (void) timerMethod
{
    NSLog(@"[A timerMethod]: the time is: %@", [self getTotalTime]);
}

- (NSDate *) getTotalTime
{
    return [NSDate date];
}
@end

@implementation B
- (void) timerMethod
{
    NSLog(@"[B timerMethod]: the time is: %@", [self getTotalTime]);
    [super timerMethod];
}

- (NSDate *) getTotalTime
{
    return [NSDate dateWithTimeIntervalSinceNow:3600];  // 3600 == an hour from now
}

我认为您担心的是 B-timerMethod调用 A -timerMethod,然后又调用[self getTotalTime],因此您认为 A-getTotalTime将始终是被调用的那个。放轻松,这不是继承的工作方式。如果您有一个 B 的实例并且您调用 B 的方法之一,则self表示指向该 B 实例的指针,即使在继承方法的上下文中也是如此。也就是说,self即使在 A 的方法之一中也指向同一个对象。因此,如果您有一个发送-timerMethod到 B 实例的计时器,则会发生以下情况:

  • B-timerMethod被调用。
  • 该方法调用 [super timerMethod],导致调用 A-timerMethod
  • A-timerMethod调用[self getTotalTime],因为self是指向 B 实例的指针,所以 B-getTotalTime被调用

因此,如果您的计时器将其消息发送到 B 的实例,您应该得到两个日志语句,它们的时间都是从现在开始的一小时:

[B timerMethod]:时间为:当前时间+1小时

[A timerMethod]:时间为:当前时间+1小时

但是,如果您的计时器将其消息发送到 A 的一个实例,您将只获得一个日志语句,并且它将具有当前时间:

[A timerMethod]:时间为:当前时间

像这样在子类中“覆盖”方法的能力是使继承有用的关键特性之一;子类可以修改或完全替换超类的行为,并且超类中的代码将自动调用被覆盖的方法,而不是在子类的实例中调用它自己的方法。

所以,你的标题问题的答案......

如何使用调用子版本的方法?

只是self在你想要当前对象提供的方法时使用。

于 2013-04-20T04:01:44.823 回答