将for循环转换为接受ID类型

时间:2016-06-07 11:45:28

标签: objective-c

我希望能够重用此方法,因此它不受for循环声明中调用的类的限制。

问题是编译器不知道id究竟是什么,所以我无法使用。关于它的符号。我需要将它投射到任何类型的事件类我将传递它,而不必重复SpecialEvent1 SpecialEvent2 SpecialEvent3

的方法

因此,我希望能够执行类似for (SpecialEvent1 *event in day)的操作而不是for (id event in day),但是当我尝试访问时间或持续时间属性时会出现问题

- (NSArray *)sumDay:(NSArray *)day {
    NSInteger morning = 0, afternoon = 0, evening = 0, night = 0;

    for (SpecialEvent1 *event in day) {
        NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:event.time];
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:date];
        NSInteger hour = [components hour];

        if (hour < 12) {
            morning += event.duration;
        }
        else if (hour < 18) {
            afternoon += event.duration;
        }
        else if (hour < 20) {
            evening += event.duration;
        }
        else {
            night += event.duration;
        }
    }

    NSArray *sums = @[@(morning), @(afternoon), @(evening), @(night)];
    return sums; 
}

1 个答案:

答案 0 :(得分:0)

假设您对没有timeduration属性的对象不感兴趣,您可以定义一个说明这样的协议:

@protocol TimedEvent <NSObject>
-(NSTimeInterval)time;
-(NSTimeInterval)duration;
@end

然后像这样浏览数组:

- (NSArray *)sumDay:(NSArray *)day {
    NSInteger morning = 0, afternoon = 0, evening = 0, night = 0;

    for (id<TimedEvent> event in day) {
        if (![event conformsToProtocol:@protocol(TimedEvent)]) {
            continue;
        }
        NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:event.time];
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:date];
        NSInteger hour = [components hour];

        if (hour < 12) {
            morning += event.duration;
        }
        else if (hour < 18) {
            afternoon += event.duration;
        }
        else if (hour < 20) {
            evening += event.duration;
        }
        else {
            night += event.duration;
        }
    }

    NSArray *sums = @[@(morning), @(afternoon), @(evening), @(night)];
    return sums; 
}