如何按时间扫描数组

时间:2011-09-04 07:08:20

标签: iphone objective-c

我有一个数组,数组的每个对象都有2个对象: double =以毫秒为单位的时间 nsstring =要打印的字符串

我希望我的应用程序将扫描数组,当它到达毫秒时,它将打印nsstring。

1 个答案:

答案 0 :(得分:2)

好吧,我假设对象被称为MyObject,并且数组被称为objectArray,所以试试这个:

- (void)checkArrayForTimes; {
  float epsilon = 0.1;
  NSDate * currentTime = [NSDate date];
  float milliseconds = [currentTime timeIntervalSinceDate:startTime];
  milliseconds -= (int)milliseconds; // This mods out all of the seconds so you are only working with milliseconds.
  for(MyObject * myObject in objectArray){
    if(fabs(myObject.time - milliseconds) < epsilon){
      NSLog(@"%@", myObject.string);
    }
  }
}

在.h文件中,添加以下行:

NSDate * startDate;

然后,在您的viewDidLoad:方法中添加以下行:

    // Note, you can change the 0.05 to fit your needs.
    startDate = [[NSDate date] retain];
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(checkArrayForTimes) userInfo:nil repeats:YES];

注意: ,您可能需要使用NSDateFormatter获取NSDate 0毫秒的数据。)最后,在您的dealloc方法中,添加:

[startDate release];

希望有帮助!