如何设置一个表示未来绝对时间的变量Objective-C

时间:2012-10-06 13:54:38

标签: objective-c synchronization benchmarking

动机:我正在开发一款应用程序,让多个(客户端)手机从(服务器)手机读取音频数据。这个想法是他们必须所有一起完全同时播放歌曲。

前提:我必须找到一种方法让所有手机都以绝对的某个时间戳开始(即它与任何一部手机的使用设定时钟都不相关......)根据一些research,我认为最好的方法是使用CFAbsoluteTimeGetCurrent();这里的想法是我得到服务器与每部电话通信所需的延迟(b / c GKSession是连续完成的)显然不是并行),将延迟添加到当前时间,然后让每部手机在该开始时间播放歌曲。这个开始时间必须是绝对的,它不能是相对的。

问题:我如何用数字来表示将来的某个时间,以后可以用来构建CFDateRef。 (它必须表示为数字的原因是我必须能够在数据包中发送它。)

示例:这是一些代码,解释了我想要实现的目标:

-(void)viewDidLoad
{
    _timer = [Timer new];
    [_timer setCurrentTimeAsReferencepoint];

    [self performSelector:@selector(performAction) withObject:NULL afterDelay:5];
}


-(void)performAction
{
    double diff = [_timer getTimeElapsedinAbsTime];
    double timeInFuture = diff + [Timer getCurTime];
    NSLog(@"this is time in future in abs terms %f",timeInFuture);

    CFDateRef futureDate = CFDateCreate(NULL, timeInFuture);
    CFDateRef dateNow = CFDateCreate(NULL, [Timer getCurTime]);

    Boolean keepTesting = true;

    while (keepTesting) {
        if (CFDateCompare(dateNow, futureDate,NULL) == 0)   // ie both times are equal
        {
            NSLog(@"now is the time!");
            keepTesting = false;
        } else {
            NSLog(@"now isn't the time.. skip");
        }
    }
}
在Timer.m中

-(void)setCurrentTimeAsReferencepoint
{
    _referencePoint = [[self class] getCurTime];
    NSLog(@"this is reference point %f",_referencePoint);  
}

+(double)getCurTime
{
    return (double)CFAbsoluteTimeGetCurrent();
}

// not used in the above code.. but used when i compare the time of the server phone with the client phone
+(double)getTimeDifference:(double)time1
                     time2:(double)time2
{    
    CFDateRef newDate = CFDateCreate(NULL, time2);
    CFDateRef oldDate = CFDateCreate(NULL, time1);

    CFTimeInterval difference = CFDateGetTimeIntervalSinceDate(newDate, oldDate);    

    NSLog(@"this is time difference %f",fabs(difference));
    CFRelease(oldDate); CFRelease(newDate); 

    // fabs = absolute value
    return fabs(difference);    
}

1 个答案:

答案 0 :(得分:0)

事实证明它比我想象的要简单(注意:问题中定义了getCurTime):

-(void)performAction
{
    double curTime = [Timer getCurTime];
    double timeInFuture = 2 + curTime;
    NSLog(@"this is time in future in abs terms %f and this is curTime %f",timeInFuture, curTime);

    CFDateRef futureDate = CFDateCreate(NULL, timeInFuture);
    CFDateRef dateNow = CFDateCreate(NULL, curTime);

    Boolean keepTesting = true;

    while (keepTesting) {
        dateNow = CFDateCreate(NULL, [Timer getCurTime]);
        if (CFDateCompare(dateNow, futureDate,NULL) >= 0)   // ie both times are equal or we've 
                                                            // gone past the future date time
        { 
            NSLog(@"now is the time!");
            keepTesting = false;
            return;
        } else {
            NSLog(@"now isn't the time.. skip");
        }
    }
}