新站点和Obj C.试图从设备运动(工作)中获得音调值,放入具有最近60个值(不工作)的数组中,并选择数组内的最大值。对于来自设备的每个新音高值,新的音高值被添加到数组中,第61个值被删除。当我连接我的手机并运行时,我得到pitch和maxPitch的log值;然而,我没有得到60个值的数组,所以我不相信它是正常工作的。非常感谢任何帮助。
我认为问题可能出在这一行。Count <= 60) {
[pitchArray addObject:[NSString stringWithFormat:@"%。2º",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
每次获得新的音高值时,都要分配一个新的数组。所以你应该将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]);
}];
}
啊,简单的错误。它没有循环,所以我把if/else语句改为while。代码现在可以工作并输出60项数组和最大值。