为什么我在方法调用中获取超类而不是子类?

时间:2014-03-11 23:08:35

标签: objective-c subclass

我有这个类,它是C#抽象类的一个端口;这是.h文件:

@interface Schedule : NSObject  {

}

@property (strong, nonatomic) NSDate *apptStartTime;
@property (strong, nonatomic) NSDate *apptEndTime;
@property (strong, nonatomic) NSString *key;

-(BOOL) occursOnDate: (NSDate *) timeOfAppointment;

@end

这是Schedule:

的.m文件
@implementation Schedule  {

}

@synthesize apptStartTime;
@synthesize apptEndTime;
@synthesize key;

/**

The OccursOnDate method is abstract and must be implemented by subclasses. When     passed a date, the schedulers must determine if an appointment falls on that date. If one does, the method should return true. If not, the method returns false.

*/

-(BOOL) occursOnDate: (NSDate *) dateOfAppointment  {

    return YES:
}

因为它是一个C#抽象类,所以我必须覆盖它(或子类),这是我在这里完成的(这是.h文件):

@interface SingleSchedule : Schedule  {

}

@property (strong,nonatomic) NSDate *apptDate;

-(BOOL) occursOnDate: (NSDate *)date;

@end

这是.m文件:

@implementation SingleSchedule  {

}

@synthesize apptDate; 

-(BOOL) occursOnDate: (NSDate *)date  {

    return (apptDate == date);  //  <--------- TODO   where is apptDate set?
}

这就是我所谓的 happenOnDate 类,期望得到子类,但我得到了超类类:

-(void) addAppointmentsForDate:(NSDate *)checkDate scheduleSet: (NSMutableSet *)setOfSchedules appointmentSet:(NSMutableSet *)setOfAppts {

Schedule *sc = [[Schedule alloc]init];
Appointment *newAppt = [[Appointment alloc]init];

NSArray *scheduleArray = [setOfSchedules allObjects];

for(int i = 0; i < scheduleArray.count; i++)  {
    if([sc occursOnDate: checkDate])   {  //  <-------- method called is the superclass, not the override
        newAppt = [self generateAppointment:checkDate andSchedule: scheduleArray [i]];
        [setOfAppts addObject:newAppt];
    }
}
}

我在这里想到的是能够获得子类方法而不是其他方法吗? (我已经看过SO和Google,但没有发现任何可以完全回答这个问题的内容。)

1 个答案:

答案 0 :(得分:3)

正在调用基类实现,因为sc的类型为Schedule,而不是SingleSchedule。当您实例化一个类时,新对象知道它自己的实现和它的基类链,但该对象不知道它的继承类。

也许你想要的是:

SingleSchedule *sc = [[SingleSchedule alloc]init];