views:

144

answers:

2

I have a UIView subclass that draws itself when -drawRect: is called. It only takes a moment, but under extreme circumstances, such as low memory and deletion of the instance when going to another view controller, the draw function doesn't complete before the the object is deallocated.

How am I supposed to deal with this issue? The deallocation causes any calls to [self ...] to throw a EXC_BAD_ACCESS, which the drawing function does to determine how to draw itself.

Note:

I'm largely using the framework to handle memory management. The issue lies in the asynchronous calls to -drawRect: from the CATiledLayer that the UIView uses, which come in before the UIView is released. However, since it's asynchronous, the -didReceiveMemoryWarning runs while it's drawing, causing the view to be released in the middle of the drawing.

+1  A: 

Start by reading Apple's Memory Management Rules:

Cocoa Memory Management Rules

The bottom line: the way to "deal" with the issue is to make sure you manage your objects and their memory use properly. A crash because of a deallocation is not something to be trapped but a flat-out bug in your app that needs fixed.

August
I see no way to fix it. I've read the documentation, and I'm largely using the framework to handle memory management. The issue lies in the asynchronous calls to drawRect from the CATiledLayer which come in after the object has been released.
Ed Marty
If you're getting an EXC_BAD_ACCESS error, that's almost 100% going to be the programmer's fault. I suggest you enabled zombies and debug that way to track down which object you're releasing when you shouldn't be.
August
I already did. The UIView is the object that's being released, right in the middle of while it's being drawn.
Ed Marty
If the UIView is the problem, then, obviously, you're not retaining it or one of its subviews properly. While no code is perfect, not even Apple's, this definitely sounds like a programmer mistake, not a bug in the SDK/OS.
August
Memory management issues are sometimes difficult to track down. Again, enable zombies and figure out exactly what the offending object is (Google NSZombieEnabled for more on how to accomplish this).
August
Like I said, I already have NSZombieEnabled, and that's how I found out it was the UIView subclass that was the issue. Even if I surround the draw call with a [self retain] and [self release] it still has the error. Even if I make it a static member and never release it, it still has the error.
Ed Marty
A: 

I think the answer here is: use @synchronized

Ed Marty