[myArray addObject:[[objcBlock copy] autorelease]] crashes on dealloc'ing the array
Asked Answered
F

1

4

I wrote a class for declaratively describing a sequence of UIView animations. My method takes a vararg of animation blocks and puts them in an array. So in my loop I want to do this:

[animations addObject:[[block copy] autorelease]];

I first copy the block so that it is moved to the heap, allowing it to be retain'ed by the array. Then I autorelease it to relinquish ownership (because the array retains it).

However this crashes when the animations array is dealloc'd. (My understanding is that the referenced blocks have already been dealloc'd.)

Strange thing is, this works:

[animations addObject:[block copy]];
[block release];

UPDATE: – … as does this:

[animations addObject:[block copy]];
[block autorelease];

Why? I would have expected all 3 code snippets to work equally well. Any explanation?

Frasier answered 2/5, 2011 at 8:24 Comment(3)
I believe there’s something else in your code that causes the crash. What you’ve posted is correct and should work. Are you able to create a minimal test case that reproduces this problem?Boatright
Thanks for the hint. I'm still investigating, currently trying to build a minimal test case.Frasier
Bavarious was right. The problem was that, in a previous attempt to fix up a memory leak, I manually released the blocks before releasing the array containing them. Strange thing, though, that over-releasing the blocks did not crash for the bottom two code snippets!Frasier
H
6

Example 1:

[animations addObject:[[block copy] autorelease]];

This is copying a block, and autoreleasing the copy.

Example 2:

[animations addObject:[block copy]];
[block release];

This is copying a block, then releasing the original. If you've handled memory well, this should result in your original block being overreleased (and crashing), and your copy being leaked.

Example 3:

[animations addObject:[block copy]];
[block autorelease];

This is copying a block, then autoreleasing the original. See note with previous example.

Your answer, then, is that your code is doing something wrong elsewhere. Fix that, and go back to your first example.

Hylan answered 18/5, 2011 at 18:26 Comment(1)
Nicely spotted @steven-fisherJule

© 2022 - 2024 — McMap. All rights reserved.