gpt4 book ai didi

objective-c - 为什么在此代码中通过另一个对象调用时 Core Motion 更新不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:50:19 27 4
gpt4 key购买 nike

@interface Tester()
{
int currentAccelerationOnYaxis;
}
@end

@implementation Tester

-(void) test
{
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 0.01;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
currentAccelerationOnYaxis = motion.userAcceleration.y;
}
];
while(1==1)
{
NSLog(@"current acceleration is: %f", currentAccelerationOnYaxis);
}
}
@end

然后我像这样在后台线程上执行上述方法:
[myTester performSelectorInBackground:@selector(test) withObject:nil];

而且效果很好。

但是,以下配置不起作用,我不明白为什么:

@implementation MotionHandler

@synthesize accelerationOnYaxis; // this is an int property of the MotionHandler class

-(void) startAccelerationUpdates
{
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 0.01;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
self.accelerationOnYaxis = motion.userAcceleration.y;
}
];
}

@implementation Tester

-(id)init
{
//...
currentMotionHandler = [[MotionHandler alloc] init];
}
-(void) test
{
[currentMotionHandler startAccelerationUpdates];
while(1==1)
{
NSLog(@"current acceleration is: %f", currentMotionHandler.accelerationOnYaxis);
}
}
@end

然后我像这样在后台线程上执行上述方法:
[myTester performSelectorInBackground:@selector(test) withObject:nil];

它不起作用,这是为什么?

最佳答案

我想通了。在我的第二个版本中,我创建的 CMMotionManager 实例由于某种原因丢失了。因此,我将 MotionHandler 类的实现更改为:

MotionHandler.m

@interface MotionHandler()
{
//..
CMMotionManager *motionManager; // I now declare it here
}

@implementation MotionHandler

@synthesize accelerationOnYaxis; // this is an int property of the MotionHandler class

-(void) startAccelerationUpdates
{
motionManager = [[CMMotionManager alloc] init]; // and then initialize it here..
motionManager.deviceMotionUpdateInterval = 0.01;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
self.accelerationOnYaxis = motion.userAcceleration.y;
}
];
}
-(void)test
{
[self startAccelerationUpdates];
while(1==1)
{
NSLog(@"current acceleration on y-axis is: %f", self.accelerationOnYaxis);
}
}

现在它似乎工作正常。

关于objective-c - 为什么在此代码中通过另一个对象调用时 Core Motion 更新不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12080487/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com