I have an object which I initialize in the app’s main thread but I call one of its methods in a background thread using performSelectorInBakground. However, the method seems to be unresponsive. More specifically :
AccHandler.m
#import "AccHandler.h"
@implementation AccHandler
@synthesize accelerationOnYaxis;
-(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;
}
];
}
@end
Tester.m
#import "Tester.h"
@interface Tester()
{
AccHandler *accHandler;
}
@end
@implementation Tester
- (id) init
{
//....
accHandler = [[AccHandler alloc] init]; // initialized in main thread
}
-(void)test
{
[accHandler startAccelerationUpdates]; // but -(void)test will be executed in a background thread..
NSLog(@"current acceleration is %f", accHandler.accelerationOnYaxis;
}
later on in my code I call the test method from a performSelectorInBackground but I get 0 acceleration values..
Yes.
Your mistake seems to be that you are not waiting for the background stuff to produce results.
Another problem might be that
motionManagerdoes not seem to be retained by some strong reference. So it might just immediately go away after initialization.