Question

I'm beginning coding with the DeviceMotion class. After following Apple's documenation, i have the following:

- (void)viewDidLoad {
    [super viewDidLoad];
    myMM = [[CMMotionManager alloc] init];
    myMM.deviceMotionUpdateInterval = 1.0/30.0;
    theQ = [[NSOperationQueue currentQueue] retain];


    motionHandler = ^ (CMDeviceMotion *motionData, NSError *error) {
        if (motionData.rotationRate.z > 5.5 || motionData.rotationRate.z < -5.5) {
            NSLog(@"Rotation of Z.");  // Reference A       
        }
    };

-(IBAction)toggleClick{
    NSLog(@"toggle");

    if(myMM.gyroAvailable){

        if(myMM.deviceMotionActive){
            NSLog(@"Stopping Motion Updates..");
            [myMM stopDeviceMotionUpdates];
        } else {
            NSLog(@"Starting Motion Updates..");
            [myMM startDeviceMotionUpdatesToQueue:theQ withHandler:motionHandler];
        }

    }
    else {
        NSLog(@"No motion available. Quit!");
    }

This code works fine, however when I want to do any code except an NSLog (even something as simple as incrementing an integer) in place of the 'reference A', I get an EXEC Bad Access in the console.

I've looked around, and all I've found is that it's a memory leak of sorts. Does anyone know whats going on? If not, how can I figure it out? I'm pretty inexperienced with Instruments, but if I'm pointed in the right direction I'd be much appreciated.

Was it helpful?

Solution

EXC_BAD_ACCESS is an OS-level exception meaning that you are trying to access memory that doesn't belong to you. I think this has something to do with your block being local to the scope, so once it goes out of scope, it is destroyed. You need to create a copy of it on the heap.

Try this answer from the renowned Dave DeLong. Also, as with the normal Cocoa memory management rules, don't forget to release it if you've made a copy.

For example:

motionHandler = Block_copy(^ (CMDeviceMotion *motionData, NSError *error) {
    if (motionData.rotationRate.z > 5.5 || motionData.rotationRate.z < -5.5) {
        NSLog(@"Rotation of Z.");  // Reference A       
    }
});


// and then later:

- (void) dealloc
{
    [motionHandler release];
    //and all others.
    [super dealloc];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top