Crash with Blocks and Core Motion
I'm using the push handler of Core Motion for accelerometer updates:
CMAccelerometerHandler a开发者_StackOverflowccelerometerHandler = ^ (CMAccelerometerData *accelerometerData, NSError *error) {
// handle update
};
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:[[accelerometerHandler copy] autorelease]];
This code crashes. If I don't copy the block at all I get intermittent crashed on suspend/resume. If I remove the autorelease
it works fine, but I think this will produce a leak.
I also tried to assign the block to an ivar and release it after [motionManager stopAccelerometerUpdates]
. Crashes as well.
How comes? I always thought I've to balance any copy
/retain
with a release
/autorelease
?
See also: Copying blocks (ie: copying them to instance variables) in Objective-C
The issue here is ownership over the block. When you consider that blocks are really just objects it should become clearer how this all needs to work. You DO need to copy the block to the heap, but then you need to treat it just like every other object that you have ownership over. When the object that called copy on the block is dealloced, you should release your ownership over the block.
精彩评论