网站的新用户和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
答案 0 :(得分:0)
每次获得新音高值时,您都会继续分配新数组。因此,您应将音高数组定义为属性,并在运动更新处理程序之前分配它。你的代码是:
@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]);
}];
}
答案 1 :(得分:0)