我正在创建一个程序,每次按下按钮,就会将当前的日期/时间添加到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];
}
}
我得到的是空数据,无法从数组中获取双值。
从本质上讲,我希望该程序能够完成以下工作:
谢谢!
发布于 2016-10-09 00:23:39
这是:
[_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
发布于 2016-10-09 00:23:09
发布于 2016-10-09 00:24:44
你真的需要这个第一步的值吗,这个值总是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)];
}
https://stackoverflow.com/questions/39941276
复制相似问题