我正在创建一个程序,每次按下按钮时都会将当前日期/时间添加到NSMutableArray。然后我试图将时间的双重值转换为另一个NSMutableArray。最后,我想使用这些双精度值来确定它们之间的平均时间。以下是我到目前为止的情况:
按钮的IBAction代码:
- (IBAction)tapButton:(id)sender {
_currentTapTime = [NSDate date];
[_tapTimeData addObject:_currentTapTime];
_tapCountInt++;
_tapCount.text = [NSString stringWithFormat:@"%ld", (long)_tapCountInt];
}
我的代码试图将时间转换为另一个数组作为双值:
for (int i = 0; i < [_tapTimeData count]; i++) {
if (i == 0) {
NSTimeInterval interval = [[_tapTimeData objectAtIndex:i] timeIntervalSinceDate:[_tapTimeData objectAtIndex:i]];
[_intervalNumber initWithDouble:interval];
[_tapTimeDataAsDouble addObject:_intervalNumber];
} else {
NSTimeInterval interval = [[_tapTimeData objectAtIndex:i] timeIntervalSinceDate:[_tapTimeData objectAtIndex:i-1]];
[_intervalNumber initWithDouble:interval];
[_tapTimeDataAsDouble addObject:_intervalNumber];
}
}
我正在获取空数据,无法从数组中获取double值。
基本上,我希望程序执行以下操作:
谢谢!
答案 0 :(得分:1)
这样:
[_intervalNumber initWithDouble:interval];
[_tapTimeDataAsDouble addObject:_intervalNumber];
应该是这样的:
_intervalNumber = [NSNumber numberWithDouble:interval];
[_tapTimeDataAsDouble addObject:_intervalNumber];
<强>代码:强>
@interface ViewController () {
NSDate *currentTapTime;
NSMutableArray *tapTimeData;
int tapCountInt;
IBOutlet UILabel *tapCount;
NSNumber *intervalNumber;
NSMutableArray *tapTimeDataAsDouble;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
tapCountInt = 0;
tapTimeData = [[NSMutableArray alloc] init];
tapTimeDataAsDouble = [[NSMutableArray alloc] init];
}
- (IBAction)tapButton:(id)sender {
currentTapTime = [NSDate date];
[tapTimeData addObject:currentTapTime];
NSLog(@"%@", tapTimeData);
tapCountInt++;
tapCount.text = [NSString stringWithFormat:@"%ld", (long)tapCountInt];
}
- (IBAction)tapAverage:(id)sender {
for (int i = 0; i < [tapTimeData count]; i++) {
NSLog(@"################%d", i);
if (i == 0) {
NSTimeInterval interval = [[tapTimeData objectAtIndex:i] timeIntervalSinceDate:[tapTimeData objectAtIndex:i]];
intervalNumber = [NSNumber numberWithDouble:interval];
[tapTimeDataAsDouble addObject:intervalNumber];
} else {
NSTimeInterval interval = [[tapTimeData objectAtIndex:i] timeIntervalSinceDate:[tapTimeData objectAtIndex:i-1]];
intervalNumber = [NSNumber numberWithDouble:interval];
[tapTimeDataAsDouble addObject:intervalNumber];
}
}
NSLog(@"%@", tapTimeDataAsDouble);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
答案 1 :(得分:0)
答案 2 :(得分:0)
你真的需要第一步值,它总是为0吗?
NSTimeInterval interval = [[_tapTimeData objectAtIndex:i] timeIntervalSinceDate:[_ tapTimeData objectAtIndex:i]];
这应该做你需要的。结果数组将包含n-1个对象。
for (int i = 1; i < [_tapTimeData count]; i++) {
NSTimeInterval interval = [_tapTimeData[i] timeIntervalSinceDate:_tapTimeData[i-1]];
[_tapTimeDataAsDouble addObject:@(intervalNumber)];
}