Цель C / iOS - обновить массив по значению шага движения устройства
Новичок на сайте и Obj C. Попытка получить значение основного тона из Device Motion (работает), поместить в массив с последними 60 значениями (не работает) и выбрать максимальное значение в массиве. С каждым новым значением основного тона устройства добавляется новое значение основного тона, а 61-е значение сбрасывается. Когда я подключаю свой телефон и запускаю, я получаю значения журнала для высоты тона и maxPitch; тем не менее, я не получаю массив из 60 значений, поэтому я не верю, что он работает правильно. Любая помощь с благодарностью.
Я полагаю, что проблема может быть в строке: if (pitchArray.count <= 60) {
[pitchArray addObject: [NSString stringWithFormat: @ "%. 2gº", motion.attitude.pitch * kRadToDeg]];
Вот полный код:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
#define kRadToDeg 57.2957795
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *pitchLabel;
@property (nonatomic, strong) CMMotionManager *motionManager;
@end
@implementation ViewController
- (CMMotionManager *)motionManager
{
if (!_motionManager) {
_motionManager = [CMMotionManager new];
[_motionManager setDeviceMotionUpdateInterval:1/60];
}
return _motionManager;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
self.pitchLabel.text = [NSString stringWithFormat:@"%.2gº", motion.attitude.pitch * kRadToDeg];
NSMutableArray *pitchArray = [NSMutableArray array];
pitchArray = [[NSMutableArray alloc] initWithCapacity:60];
if (pitchArray.count <= 60) {
[pitchArray addObject:[NSString stringWithFormat:@"%.2gº", motion.attitude.pitch * kRadToDeg]];
}
else {
[pitchArray removeObjectAtIndex:0];
}
NSNumber *maxPitch = [pitchArray valueForKeyPath:@"@max.intValue"];
NSLog(@"%@",pitchArray);
NSLog(@"Max Pitch Value = %d",[maxPitch intValue]);
}];
}
@end
2 ответа
Ах, простая ошибка. Это не было зацикливанием, поэтому я изменил оператор if/else на while. Код работает сейчас и выводит массив из 60 элементов и максимальное значение.
Вы продолжаете выделять новый массив каждый раз, когда получаете новое значение высоты тона. Таким образом, вы должны определить массив pitch как свойство и выделить его перед обработчиком обновления движения. Ваш код будет:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *pitchLabel;
@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) NSMutableArray *pitchArray;
@end
@implementation ViewController
- (CMMotionManager *)motionManager
{
if (!_motionManager) {
_motionManager = [CMMotionManager new];
[_motionManager setDeviceMotionUpdateInterval:1/60];
}
return _motionManager;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.pitchArray = [[NSMutableArray alloc] initWithCapacity:60];
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
self.pitchLabel.text = [NSString stringWithFormat:@"%.2gº", motion.attitude.pitch * kRadToDeg];
if (self.pitchArray.count <= 60) {
[self.pitchArray addObject:[NSString stringWithFormat:@"%.2gº", motion.attitude.pitch * kRadToDeg]];
}
else {
[self.pitchArray removeObjectAtIndex:0];
}
NSNumber *maxPitch = [self.pitchArray valueForKeyPath:@"@max.intValue"];
NSLog(@"%@",self.pitchArray);
NSLog(@"Max Pitch Value = %d",[maxPitch intValue]);
}];
}