3
@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];

它不工作,这是为什么呢?

4

1 回答 1

4

我想到了。在我的第二个版本中,我创建的 CMMotionManager 实例由于某种原因丢失了。因此,我将 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);
    }
}

现在它似乎工作正常。

于 2012-09-03T19:28:13.390 回答