Remember the post I made awhile back, talking about how I needed to turn off optimizations for two pieces of code and I didn’t understand why? Of course you do, it was here, remember? Well, I was listening to the latest episode of Late Night Cocoa wherein they were talking about garbage collection. The guest, Andre Pang, made a comment about how crashes with code that uses C pointers into NSData objects were fairly common. Ding ding ding!
See, the problem is this. I have code this like at the top of my problem functions:
NSData* theData = [some data blob];
byte* myPointer = [theData bytes];
The problem here is that I then use “myPointer” for the remainder of the function as I read from the data blob. As far as the runtime is concerned, I’m done with “theData” since I never talk about it again throughout the entire function. It doesn’t care about my C pointer, it only sees that I’m no longer talking about “theData“. So it marks it as collectable and the GC comes along at some random point and removes my data from underneath my feet.
The solution is to add a line of code to the end of the function that looks like this:
[theData self];
This is a do-nothing line of code but it DOES force the runtime not to mark the object as collectable since it’s going to be talked about again at the end of the function. This fixes my random crashes! I was able to remove the stupid pragma statements and now everything hums along as it should.
Amazing what you can learn from a humble podcast! Thanks, Late Night Cocoa!
Tags: Cocoa, garbage collection, objective-c